Search code examples
c#asp.net-web-apiasp.net-web-api-routing

Web API 2 routing - Route attribute


Question is regarding defining custom routes with the Route attribute.

I know that in the WebApiConfig class you always define the default route,

configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
  new { id = RouteParameter.Optional });

What I cannot get working is when I want to pass another parameter. I know I can do this (code below is defined underneath the default route listed above):

    //configuration.Routes.MapHttpRoute(
    //    name: "GetBrandImagePaths",
    //    routeTemplate: "api/{controller}/{id}/{type}");

But I'd rather, instead of defining all these routes in the WebApiConfig file, use custom routing. However, if I do not have the commented out code above in the file, I get a 404. Thus leading me to believe the custom Route is not even being looked at.

public class HelperApiController : ApiController
{
    [HttpGet]
    [Route("api/helperapi/{id}/{type}")]
    public string GetBrandImages(int id, string type)
    {
        .....
    }
}

How can I have it so I can use routes defined in the WebApiConfig file, AND defining custom routes inside individual API controllers.

Note that this project is also a MVC project (not just WebApi). Is there something I'm missing, doing incorrectly etc? I know there's numerous posts out there defining how to pass multiple params, but I think my question is a little more specific on to why one works and not the other.


Solution

  • You need to call config.MapHttpAttributeRoutes().

    This will parse all the Controller classes and derive the routes from the attributes.

    I would not mix this with the standard routing.