Include WebAPI to an existent project with ASP.NET MVC
If you have a new project and want to create a project with MVC and WebAPI together, you just need to select the correct template on Visual Studio. But if you already have an MVC project and want to include a WebAPI on the same project, how can you do that?
- Add reference to System.Web.Http.WebHost.
- Add App_Start\WebApiConfig.cs (see code snippet below).
- Import namespace System.Web.Http in Global.asax.cs.
- 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.
- Add a controller deriving from System.Web.Http.ApiController.
You could then learn enough from the tutorial (Your First ASP.NET Web API) to define the 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.