Reputation: 4607
I am trying to use WebAPI as part of an MVC5 application. The application has areas, so to keep with the existing structure I have created and "API" area. However, I am having some routing troubles as I get a 404 when hitting the API URL.
I have read a number of posts on this, mostly MVC4 examples and so far I have not had any success.
Initially, I had the API routes as part of the area routing, so above the below default route, I had another with the RouteTemplate API/{controller}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"API_default",
"API/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
I then realised my error and moved the API route to a different method in the same area registration file
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Direct_API",
routeTemplate: "API/{controller}"
);
}
I have now moved the API routes out of the area registration file completely, created a new API route config file in app_start
and registered it in global.asax
before the application routes file. However, still, if I goto http://localhost:port/API/Import
I do not hit the API Controller.
The API Import Controller sits in the API area of the application
public class ImportController : ApiController
{
[HttpGet]
public Array Get()
{
return new[]{true, false, false, true};
}
}
Global.asax registration
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
I have also tried registering the file MVC4 way which was WebApiConfig.Register(GlobalConfiguration.Configuration);
Upvotes: 1
Views: 1055
Reputation: 4607
I found the answer to this but think I will leave the question up to help others in the future. Many of the examples and articles covering this subject and very specific that the RouteConfig
must be after the WebAPI config. I was very careful about this.
However, I completely overlooked that area registrations were running first.
Moving AreaRegistration.RegisterAllAreas();
to after GlobalConfiguration.Configure(WebApiConfig.Register);
solved the issue.
This still leaves the API registration global, which doesn't feel right as its localised to an area. I think i can solve that with attribute routing and the removal of the Area Registration File for the API.
Upvotes: 3