Overview
I'm currently trying to get attribute routing to work with my api controllers. It doesn't appear to be working, and I'm unsure why. I'm not sure if I'm missing a crucial step, or what the problem could be.
Problem
I'm trying to hit localhost/api/user/custom?test=1 but I get a 404 (I expect this to work)
If I hit localhost/api/customapi?test=1 I successfully get into my method
Why does the first url not work?
Setup
My setup is as follows:
CustomController.cs
[System.Web.Mvc.RoutePrefix("api")]
public class CustomApiController : ApiController
{
[System.Web.Mvc.Route("user/custom")]
[System.Web.Http.HttpGet]
public async Task<CustomResponse> Get([FromUri] CustomRequest request)
{
//Work
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...(json serializer settings)...
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
RouteConfig.cs
public static class RouteConfig
{
public static void Register(RouteCollection routes, bool registerAreas = true)
{
if(registerAreas)
{
AreaRegistration.RegisterAllAreas();
}
//Ignore Routes
...
//Register specific routes
routes.MapRoute("HomeUrl", "home", new { controller = "Home", action = "Index" });
.
.
routes.MapRoute(
"Default", //Route name
"{controller}/{action}/{id}", //URL with parameters
new { controller = "Home", action = "Index", id =UrlParameter.Optional }
);
}
}
Global.asax.cs
public class Global : HttpApplication
{
protected void Application_Start()
{
....(app startup stuff)...
GlobalConfiguration.Configure(WebApiConfig.Register);
BundleConfig.Register(BundleTable.Bundles);
....(more app startup stuff)...
RouteConfig.Register(RouteTable.Routes);
}
}