Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
up vote 306 down vote accepted

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.

share|improve this answer
11  
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
5  
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
3  
You can use nuget now, and stay on top of any changes that happen! nuget.org/packages/Microsoft.AspNet.WebApi – Chris Aug 13 '13 at 2:25
2  
@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 6 '15 at 19:11

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: http://wildermuth.com/2012/2/22/WebAPI_for_the_MVC_Guy

share|improve this answer
3  
As of 2013 that is a legacy package and you want Install-Package Microsoft.AspNet.WebApi now. See nuget.org/packages/Microsoft.AspNet.WebApi – Chris Aug 13 '13 at 2:24

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

share|improve this answer
    
This is by far the easiest way to achieve this now. – Adam Smith Oct 27 '14 at 3:28
    
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

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
share|improve this answer
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 6: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 7:34
    
I agree, it seems that this plumbing is already installed if you use the Web App project template. – longda Feb 8 '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

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.

share|improve this answer

To add WebAPI in my MVC 5 project.

Finally able to make it work after few hours of struggling... This SO post helped..

1 Open NuGet Package manager consol and run

PM> Install-Package Microsoft.AspNet.WebApi

2 Add references to System.Web.Routing, System.Web.Net, 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

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>
share|improve this answer

The above solution works perfectly. I prefer to choose Web API option while selecting the project template as shown in the picture below

Project template showing web API option

share|improve this answer
    
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 at 11:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.