Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

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.

like image 517
aknuds1 Avatar asked Aug 16 '12 14:08

aknuds1


People also ask

Can we use Web API with ASP NET web form?

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.


2 Answers

The steps I needed to perform were:

  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); } 

Update 10.16.2015:

Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.

like image 71
aknuds1 Avatar answered Oct 19 '22 17:10

aknuds1


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.

like image 35
cdeutsch Avatar answered Oct 19 '22 15:10

cdeutsch