Search code examples
angularjsasp.net-web-apiroutesasp.net-web-api-routing

Setting WebAPI routing


In WebApiConfig I've added to routes :

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

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

In ApiController I have 2 GET Actions :

[HttpGet]
public async Task<IEnumerable<RequestModel>> Pending(){}

[HttpGet]
public async Task<IEnumerable<RequestModel>> Resolved()

When I tried to call one of this action from AngularJS service I got 500 Error.

Multiple actions were found that match the request

When I left only second route, that match my Action - it works well.

"/api/v1/RequestRecipient/Pending"

In what can be problem in case of 2 routes?


Solution

  • After some research I've found solution - Just need to change order of routes.

    From :

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

    To :

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

    But also I've found someone opinion, that this isn't good idea to have Action and Non-Action routes.