372

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.

aknuds1
  • 65,625
  • 67
  • 195
  • 317

9 Answers9

474

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.

aknuds1
  • 65,625
  • 67
  • 195
  • 317
  • 13
    This was really helpful. I had to add a reference to `System.Net.Http` as well, but apart from that, it worked like a charm! – Christofer Eliasson Aug 24 '12 at 13:06
  • 1
    Cool, I just tested by creating a new MVC 4 Internet project though, and it already references `System.Net.Http`. So maybe your case differs slightly? – aknuds1 Aug 24 '12 at 13:32
  • Yeah, mine was an MVC 3 application that I had manually updated to MVC 4. Don't know if that could be the reason. – Christofer Eliasson Aug 24 '12 at 13:43
  • 6
    I upgraded a project from MVC3 to 4 as well and also needed to add a reference to System.Web.Http. – Damien Sawyer Oct 16 '12 at 22:16
  • 1
    I created an "Internet Application" and it seems that all of this is done for you out of the box. – makerofthings7 Jan 29 '13 at 03:08
  • Anyone know if this will allow you to create the equivalent of a new area in the project called "api" that has it's own distinct controllers and such tucked under an api directory? Then you could have your standard web controllers for web site in the usual area and an entirely different set under api. Wow, I really hope that made sense. – longda Feb 08 '13 at 19:57
  • 1
    @longda The Web API route in this answer means that requests to /api/* get routed to API controllers. I don't think it matters if you put your API controllers in a sub-directory ("api"), although I've done this in my projects. Just try for yourself. – aknuds1 Feb 08 '13 at 23:21
  • 5
    You can use nuget now, and stay on top of any changes that happen! https://www.nuget.org/packages/Microsoft.AspNet.WebApi – Christopher Aug 13 '13 at 02:25
  • 1
    @longda Although it isn't required to be in an Area "api" it plays nicer with the Html helpers - well, kinda. The helpers themselves are in need of a little help when it comes to areas imho. – Dave Jellison Nov 15 '13 at 18:02
  • @aknuds1, this is one great article but I'm surely doing something wrong. I'm trying to make it work on MVC 5 with no success. I did it according to this explanation and then I right clicked on "Controllers" and added the item "Web API 2 Controller with actions, using Entity Framework" where I selected my model class and db context. Everything went fine but when I tried to access /api/(MyController)... BOOM: 404 – Luis Gouveia Mar 13 '14 at 17:58
  • 1
    @LuisGouveia Sorry I haven't tried MVC 5, maybe the routing has changed? Are you sure you're accessing the controller with the right URL? I.e., if it's named `MyController`, you should access it as /api/My. – aknuds1 Mar 13 '14 at 20:00
  • @aknuds1, That's exactly what I did... it must be something else... Do you think it can be related with my configuration SSL=TRUE (HTTPS)? Thanks – Luis Gouveia Mar 14 '14 at 09:58
  • 1
    @LuisGouveia I have no idea really. My advice would be to create a new Web API 2 project, and see how that works. – aknuds1 Mar 14 '14 at 10:23
  • 1
    Make sure to note the _"before registering the default Web Application route as that would otherwise take precedence"_ comment or you will get a `HTTP 404` "resource not found' error even though you might have everything else actually wired up correctly. – atconway Mar 27 '14 at 16:10
  • 4
    I wouldn't get this to work until I changed my web api register to: GlobalConfiguration.Configure(WebApiConfig.Register); – KingOfHypocrites Jul 14 '14 at 12:10
  • Why is "api/{controller}/{id}" not "api/{controller}/{action}/{id}"? – CodeGrue Aug 04 '14 at 12:32
  • @CodeGrue As I recall, with Web API controllers represent (REST) resources, for example users, and actions don't fit into that scheme. For example, you could issue a GET request for /api/users/1, which means to get user 1. – aknuds1 Aug 04 '14 at 13:50
  • Maybe `WebApiConfig.Register(GlobalConfiguration.Configuration);` must be after `AreaRegistration.RegisterAllAreas();`. – VansFannel Oct 10 '14 at 07:20
  • 4
    @LuisGouveia I guess it's to late but someone else will probably resolve it quicker if this is what I had. GlobalConfiguration.Configure(WebApiConfig.Register); in Global.asax goes before RouteConfig.RegisterRoutes(RouteTable.Routes); – Maxim Jan 06 '15 at 19:11
  • Hello Maxim, yes, I know, probably you fixed it after checking my own answer :) http://stackoverflow.com/questions/22401403/add-web-api-to-an-existing-mvc-5-web-application/22410173#22410173 – Luis Gouveia Jan 08 '15 at 14:31
  • I had to run the following "Install-Package Microsoft.AspNet.WebApi" in addition to the steps above to get this to work. Thanks – BrianLegg Oct 14 '15 at 17:50
  • Anything on authorization? – Shimmy Weitzhandler Oct 16 '15 at 05:31
  • 2
    I also needed GlobalConfiguration.Configuration.EnsureInitialized(); at the end of my global asax – Dan Beaulieu Nov 10 '15 at 19:38
  • Following the steps above worked great except for one issue. The answer to the issue I had is at: [Ensure that HttpConfiguration.EnsureInitialized()](http://stackoverflow.com/questions/19969228/ensure-that-httpconfiguration-ensureinitialized) – Jeremy Ray Brown Sep 06 '16 at 17:01
  • I did't find System.Web.Http.WebHost in my Add Reference window. I had to use PMC with the following command: `Install-Package Microsoft.AspNet.WebApi.WebHost`. Thanks for sharing this @aknuds1. – Aweda Jul 11 '18 at 12:24
  • where is RegisterGlobalFilters() defined? – Mike W Sep 12 '19 at 18:09
  • Thanks, really helpful. Please how do I make the web api use token based authentication while keeping the mvc part using cookie based authentication? – Prince Gnakou Sep 23 '19 at 17:18
  • BTW, I was receiving and error also, but it can be fixed by using this solution: https://forums.asp.net/t/1808094.aspx?Method+not+found+Void+System+Net+Http+Headers+HttpHeaders+AddWithoutValidation – MetalGeorge Mar 19 '20 at 15:02
82

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>
    
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
kheya
  • 7,546
  • 20
  • 77
  • 109
  • 2
    The point that created a difference was placing the WebApiconfig.Register in the first line, as was mentioned by @kheya – Rajat Jan 16 '18 at 09:35
  • I would like to add, your api controller name have to end with _Controller_, like **CarController** (not just **Car**)!!! So many people forget about it and obtain error message _"No type was found that matches the controller named {0}'"_ – 1_bug Aug 24 '18 at 10:39
  • 1
    To be more efficient with this nice answer you can disregard steps 4, 8 and 9. (they are not so essential) And if you swap the order of step 5 and 6 they will make more sense (it is better to create a class then use it, instead of use the class then create it) – Hakan Fıstık Mar 05 '19 at 11:38
  • Where exactly are we adding references to System.Web.Routing, System.Web.Net and System.Net.Http? – gabed123 Mar 07 '19 at 23:04
81

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.

itzmebibin
  • 9,199
  • 8
  • 48
  • 62
cdeutsch
  • 3,847
  • 27
  • 25
  • 3
    As of 2013 that is a legacy package and you want `Install-Package Microsoft.AspNet.WebApi` now. See https://www.nuget.org/packages/Microsoft.AspNet.WebApi – Christopher Aug 13 '13 at 02:24
29

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

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
  • This is by far the easiest way to achieve this now. – Adam Smith Oct 27 '14 at 03:28
  • 1
    Does not work here. 1. Nuget: `Install-Package Microsoft.AspNet.WebApi` 2. Add new item "Web API Controller Class (v2.1)". Result: adds the api controller but does not change `Application_Start`. With Owin. – Artyom Jul 31 '15 at 11:03
  • 2
    this is the right answer when you have vs2015 - update 3 and adding web api 2 controller. – ModChowdhury May 15 '17 at 09:58
  • It did in 2017, but I had to upgrade my WebApi assemblies. I also had to create the WebApiConfig class manually, https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/configuring-aspnet-web-api – johnny Dec 06 '18 at 16:45
22

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
cuongle
  • 74,024
  • 28
  • 151
  • 206
  • 3
    So, what else do I need to do except add the controller? This is why I posted this question in the first place, the tutorial doesn't really say since it assumes a Web API project. I've added an API controller, but it isn't routed to. – aknuds1 Aug 17 '12 at 06:57
  • 1
    The tutorial wasn't of much help as regards adding a Web API to an existing project, so I figured it out from a Web API project, as outlined in my answer. – aknuds1 Aug 17 '12 at 07:34
  • I agree, it seems that this plumbing is already installed if you use the Web App project template. – longda Feb 08 '13 at 22:56
  • @cuongle : web api version 2.2 will be install with mvc 4 ? does it support MVC 4? – Thomas Nov 30 '15 at 11:00
21

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.

Community
  • 1
  • 1
Yarkov Anton
  • 639
  • 6
  • 11
13

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";
            }  
        }
    }
    
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
3

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

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Sankar Krishnamoorthy
  • 1,255
  • 13
  • 18
  • 2
    If you are creating a project that involves Web API, it would be easier to choose the Web API option. The option will create all required files as mentioned in the above replies. – Sankar Krishnamoorthy Apr 25 '16 at 11:30
  • The problem at hand here is in Visual studio 2012 and mvc 4. Although your solution is just fine, you cannot do it in that way in VS 2012 – netfed Jul 06 '16 at 16:11
  • This is a good point and I have tried above solution with VS 2013. Thanks @netfed for pointing out. – Sankar Krishnamoorthy Jul 06 '16 at 23:56
  • Hi All, I've got the API element working in my MVC solution, but as default it tried to run the solution as a API solution. But I want it to run as a MVC solution as default and then if you go to the API location etc, run the APIs.. Has anyone else had this issue and been able to resolve it? Thanks – Chris Cooper Feb 20 '17 at 11:48
  • "to an existing ASP.NET MVC 4 Web Application" – Ali123 Apr 01 '21 at 05:02
1

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

iDeveloper
  • 1,699
  • 22
  • 47