Include WebAPI to an existent project with ASP.NET MVC

If you have a new project and wan’t to create a project with MVC and WebAPI together, you just need to select the correct template on Visual Studio.
But and if you already have an MVC project and wan’t to include an WebAPI on the same project. How can you do that?

1. Add reference to 
System.Web.Http.WebHost.
2. Add App_Start\WebApiConfig.cs (see code snippet below).
3. Import namespace System.Web.Http in Global.asax.cs.
4. Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
5. Add a controller deriving from System.Web.Http.ApiController.


I could then learn enough from 
the tutorial  (Your First ASP.NET Web API) to define my API controller.

App_Start\WebApiConfig.cs:

using System.Web.Http;
class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });
    }
}

Global.asax.cs:

using System.Web.Http;
...
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}


The NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.

Advertisements

About João Sousa
Senior Software Engineer in .Net (Microsoft Certified MTCS and MCPD). .NET Microsoft MVP 2015

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: