[asp.net-mvc] 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.

The answer is


I had same problem, the solution was so easy

Right click on solotion install Microsoft.ASP.NET.WebApi from "Manage Nuget Package for Sulotion"

boom that's it ;)


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 2012 and it is 2016, therefore adding a solution Visual Studio 2013 or higher.

Project template showing web API option


To add WebAPI in my MVC 5 project.

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already

  3. Right click controllers folder > add new item > web > Add Web API controller

  4. Web.config will be modified accordingly by VS

  5. Add Application_Start method if not there already

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  6. Add the following class (I added in global.asax.cs file)

    public static class WebApiConfig
    {
         public static void Register(HttpConfiguration config)
         {
             // Web API routes
             config.MapHttpAttributeRoutes();
    
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
    
  7. Modify web api method accordingly

    namespace <Your.NameSpace.Here>
    {
        public class VSController : ApiController
        {
            // GET api/<controller>   : url to use => api/vs
            public string Get()
            {
                return "Hi from web api controller";
            }
    
            // GET api/<controller>/5   : url to use => api/vs/5
            public string Get(int id)
            {
                return (id + 1).ToString();
            }
        }
    }
    
  8. Rebuild and test

  9. Build a simple html page

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>    
        <script src="../<path_to_jquery>/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
            var uri = '/api/vs';
            $(document).ready(function () {
                $.getJSON(uri)
                .done(function (data) {
                    alert('got: ' + data);
                });
    
                $.ajax({
                    url: '/api/vs/5',
                    async: true,
                    success: function (data) {
                        alert('seccess1');
                        var res = parseInt(data);
                        alert('got res=' + res);
                    }
                });
            });
        </script>
    </head>
    <body>
    ....
    </body>
    </html>
    

You can install from nuget as the the below image:

enter image description here

Or, run the below command line on Package Manager Console:

Install-Package Microsoft.AspNet.WebApi

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.


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.


As soon as you add a "WebApi Controller" under controllers folder, Visual Studio takes care of dependencies automatically;

Visual Studio has added the full set of dependencies for ASP.NET Web API 2 to project 'MyTestProject'.

The Global.asax.cs file in the project may require additional changes to enable ASP.NET Web API.

  1. Add the following namespace references:

    using System.Web.Http; using System.Web.Routing;

  2. If the code does not already define an Application_Start method, add the following method:

    protected void Application_Start() { }

  3. Add the following lines to the beginning of the Application_Start method:

    GlobalConfiguration.Configure(WebApiConfig.Register);


NOTE : this is just an abbreviation of this answer above

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already

  3. Add the following class

    public static class WebApiConfig
    {
         public static void Register(HttpConfiguration config)
         {
             // Web API routes
             config.MapHttpAttributeRoutes();
    
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
    
  4. Add Application_Start method if not there already (in global.asax.cs file)

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  5. Right click controllers folder > add new item > web > Add Web API controller

    namespace <Your.NameSpace.Here>
    {
        public class VSController : ApiController
        {
            // GET api/<controller>   : url to use => api/vs
            public string Get()
            {
                return "Hi from web api controller";
            }  
        }
    }
    

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?

Examples related to asp.net-web-api

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Examples related to visual-studio-2012

How to actually search all files in Visual Studio Tests not running in Test Explorer How to use _CRT_SECURE_NO_WARNINGS Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0 How can I resolve the error: "The command [...] exited with code 1"? Could not load file or assembly Exception from HRESULT: 0x80131040 MSVCP120d.dll missing How can I change IIS Express port for a site The program can't start because MSVCR110.dll is missing from your computer Controlling execution order of unit tests in Visual Studio