404 error after adding Web API to an existing MVC Web Application

Luis Gouveia picture Luis Gouveia · Mar 14, 2014 · Viewed 38.8k times · Source

There's a great question here: How to add Web API to an existing ASP.NET MVC 4 Web Application project?

Unfortunately, it wasn't enough to solve my problem. I've tried twice to be sure I haven't done anything wrong. I right clicked on "Controllers" and added the item "Web API 2 Controller with actions, using Entity Framework" where I selected my model class and db context. Everything went fine... but still... everytime I've tried to access /api/Rest I was getting a 404 error (The name of my Controller is RestController).

Answer

Luis Gouveia picture Luis Gouveia · Mar 14, 2014

It's working!!! I didn't want to believe, but guess what, the problem was related with the Global.asax routing order.

While it doesn't work with:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    GlobalConfiguration.Configure(WebApiConfig.Register); //I AM THE 4th
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}      

It works with:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register); //I AM THE 2nd
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}      

Crazy, I know.