I wish to add an ASP.NET Web API to an ASP.NET MVC 4 Web Application project, developed in Visual Studio 2012. Which steps must I perform to add a functioning Web API to the project? I'm aware that I need a controller deriving from ApiController, but that's about all I know.
Let me know if I need to provide more details.
The steps I needed to perform were:
System.Web.Http.WebHost
.App_Start\WebApiConfig.cs
(see code snippet below).System.Web.Http
inGlobal.asax.cs
.WebApiConfig.Register(GlobalConfiguration.Configuration)
inMvcApplication.Application_Start()
(in fileGlobal.asax.cs
), before registering the default Web Application route as that would otherwise take precedence.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:
Global.asax.cs:
Update 10.16.2015:
Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.
As soon as you add a "WebApi Controller" under controllers folder, Visual Studio takes care of dependencies automatically;
UPDATE 11/22/2013 - this is the latest WebApi package:
Original answer (this is an older WebApi package)
More details.
The above solution works perfectly. I prefer to choose Web API option while selecting the project template as shown in the picture below
Note: The solution works with Visual Studio 2013 or higher. The original question was asked in in 2012 and it is 2016, therefore adding a solution Visual Studio 2013 or higher.
To add WebAPI in my MVC 5 project.
Open NuGet Package manager consol and run
Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already
Right click controllers folder > add new item > web > Add Web API controller
Web.config will be modified accordingly by VS
Add Application_Start(){} method if not there already
Add the following class (I added in global.asax.cs file)
Modify web api method accordingly
Rebuild and test
Build a simple html page
Before you start merging MVC and Web API projects I would suggest to read about cons and pros to separate these as different projects. One very important thing (my own) is authentication systems, which is totally different.
IF you need to use authenticated requests on both MVC and Web API, you need to remember that Web API is RESTful (don't need to keep session, simple HTTP requests, etc.), but MVC is not.
To look on the differences of implementations simply create 2 different projects in Visual Studio 2013 from Templates: one for MVC and one for Web API (don't forget to turn On "Individual Authentication" during creation). You will see a lot of difference in AuthencationControllers.
So, be aware.