Adding Web API support to an existing ASP.NET MVC 5 project for API route registrations, remember the order of Global.asax.cs configurations

Posted: (EET/GMT+2)

 

When you add your first Web API controller to your C# ASP.NET MVC web application, Visual Studio automatically opens a Readme.txt file opens in the code editor.

This readme file is helpful and instructs you to add the following line to your Application_Start event handler inside Global.asax.cs:

GlobalConfiguration.Configure(WebApiConfig.Register);

Although this is great, and the readme file gives you the correct line of code, there are two things worth noting.

Firstly, if you are reading the instructions in a hurry, you might be tempted to directly jump to step #3, the code line you need to add to Application_Start. With the default, non-API-enabled MVC application, the compiler won't accept (doesn't know about) the object "GlobalConfiguration". This is because in the basic non-Web-API MVC application, the System.Web.Http namespace is missing from the using clauses of the Global.asax.cs file. This is mentioned as step #1, but in case you had forgotten about it, simply make sure you add the "using System.Web.Http;" line, and you should be fine.

Secondly, what the readme file doesn't mention is that ASP.NET routing rules are processed in the order they are defined. Since the normal ASP.NET MVC routes already define an "catch-all" style of route (as the default route), adding the above Web API routing registration after the MVC regular routing call simply makes the Web API routes non-functional.

The solution to the second problem is of course to change the order in which the routes are registered. Make sure API routes are registered before the MVC routes. Here's a working example:

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

Hope this helps!