Thursday, August 28, 2014

The Order of Routs is real matter in MVC Web API application

I experience the routing in the MVC applicaiton

i had the following actions in the API controller

  [HttpGet]
        public List<Customer> Get()
        {
            //gets all customer
         }

        [ActionName("CurrentMonth")]
        public List<DocumentModel> GetCustomerByCurrentMonth(string id)
        {
        
        }

        [ActionName("customerById")]
        public DocumentModel GetCustomerById(string id)
        {
       }

        [ActionName("customerByUsername")]
        public DocumentModel GetCustomerByUsername(string username)
        {
       
        }

when i state the following the routing in the WebApiConfig.cs

   config.Routes.MapHttpRoute(
              name: "ActionApi",
              routeTemplate: "api/{controller}/{action}/{id}",
              defaults: new { id = RouteParameter.Optional }
        );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
config.Routes.MapHttpRoute(
                 name: "ActionApiName",
                 routeTemplate: "api/{controller}/{action}/{username}",
                 defaults: new { Action = "GetCustomerByUsername", username = RouteParameter.Optional }
           );

when i ran lauch the web api app and try to access the api, it redirect me to the 404 page




 I set a break point in my web api, but execution never hit the break point. it means that the routing is not properly configured. I move the ActionApiName configuration to the top

 config.Routes.MapHttpRoute(
                 name: "ActionApiName",
                 routeTemplate: "api/{controller}/{action}/{username}",
                 defaults: new { Action = "GetCustomerByUsername", username = RouteParameter.Optional }
           );

            config.Routes.MapHttpRoute(
              name: "ActionApi",
              routeTemplate: "api/{controller}/{action}/{id}",
              defaults: new { id = RouteParameter.Optional }
        );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

then the break point was hit and Json data was return.







No comments:

Post a Comment