404 error after adding Web API to an existing MVC Web Application 404 error after adding Web API to an existing MVC Web Application asp.net asp.net

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


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.


If you want to use WebAPI inside an existing MVC (5) project you have to do the following steps:
1.Add WebApi packages:

Microsoft.AspNet.WebApiMicrosoft.AspNet.WebApi.ClientMicrosoft.AspNet.WebApi.CoreMicrosoft.AspNet.WebApi.WebHostNewtonsoft.Json

2.Add WebApiConfig.cs file to App_Start folder:

using System.Web.Http;namespace WebApiTest{    public static class WebApiConfig    {        public static void Register(HttpConfiguration config)        {            // Web API configuration and services            // Web API routes            config.MapHttpAttributeRoutes();            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );        }    }}

3.Add the following line to Glabal.asax:

GlobalConfiguration.Configure(WebApiConfig.Register);

Important note: you have to add above line exactly after AreaRegistration.RegisterAllAreas();

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


"When adding new routes ALWAYS KEEP IN MIND that you have to add specific route on the top followed by more generic route in the end. Otherwise, your web app will never receive proper routing."

The above is the citation from here:http://www.codeproject.com/Tips/771809/Understanding-the-Routing-Framework-in-ASP-NET-MVC

I know the answer is already given, but this could help to understand why we need to put GlobalConfiguration.Configure(WebApiConfig.Register);beforeRouteConfig.RegisterRoutes(RouteTable.Routes);