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.
Although ASP.NET Web API is packaged with ASP.NET MVC, it is easy to add Web API to a traditional ASP.NET Web Forms application. To use Web API in a Web Forms application, there are two main steps: Add a Web API controller that derives from the ApiController class. Add a route table to the Application_Start method.
The steps I needed to perform were:
System.Web.Http.WebHost
.App_Start\WebApiConfig.cs
(see code snippet below).System.Web.Http
in Global.asax.cs
.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.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); }
Update 10.16.2015:
Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.
UPDATE 11/22/2013 - this is the latest WebApi package:
Install-Package Microsoft.AspNet.WebApi
Original answer (this is an older WebApi package)
Install-Package AspNetWebApi
More details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With