156

Assuming you forgot to tick the Web API checkbox (add it to the project) when making a new MVC (5) project, what do you need to do add Web API and get it working?

There are a bunch of migration questions, but none seemed to have the complete and up-to-date steps for adding Web API to an MVC 5 project and it seems to have changed from some of the old answers.

Add Web API to MVC 4

Adding GlobalConfiguration.Configure(WebApiConfig.Register) MVC 4

Community
  • 1
  • 1
lko
  • 8,161
  • 9
  • 45
  • 62

1 Answers1

268

Update the MVC project

Use Nuget to get the newest Web API.

Project - Right click - Manage Nuget Packages - Search for Web API (Microsoft ASP.NET Web API ...) and install it to your MVC project.

Then you still need to get Web API routing to work. From Microsoft's Configuring ASP.NET Web API 2

Add WebApiConfig.cs to the App_Start/ folder

using System.Web.Http;

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // TODO: Add any additional configuration code.

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        // WebAPI when dealing with JSON & JavaScript!
        // Setup json serialization to serialize classes to camel (std. Json format)
        var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
        }
    }
}

If you have an MVC Project it will have Global.asax.cs, add the new routes. Order of the Global.asax.cs routes is critical. Note there are outdated examples which use WebApiConfig.Register

Add this line to Global.asax.cs: GlobalConfiguration.Configure(WebApiConfig.Register);

protected void Application_Start()
{
    // Default stuff
    AreaRegistration.RegisterAllAreas();

    // Manually installed WebAPI 2.2 after making an MVC project.
    GlobalConfiguration.Configure(WebApiConfig.Register); // NEW way
    //WebApiConfig.Register(GlobalConfiguration.Configuration); // DEPRECATED

    // Default stuff
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

WebAPI Help

To get the (very) helpful WebAPI help pages, install WebAPI.HelpPage. See http://channel9.msdn.com/Events/Build/2014/3-644 (~42 minutes in) for what it does. It looks very helpful!

Nuget Console: Install-Package Microsoft.AspNet.WebApi.HelpPage

To verify WebAPI is working:

To the controllers folder -> Add new item -> Web API Controller Class.

public class TestController : ApiController
{
    //public TestController() { }

    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }
    //...
}

Now you can test in IE/FF/Chrome as usual, or in the JavaScript consoles for non-get testing.

(With just the controller in the URL it will call the GET() action in the new Web API Controller, it's automatically mapped to methods/actions depending on the REST e.g. PUT/POST/GET/DELETE. You don't need to call them by action like in MVC) The URL directly:

http://localhost:PORT/api/CONTROLLERNAME/

Alternatively use jQuery to query the controller. Run the project, Open the console (F12 in IE) and try run an Ajax query. (Check your PORT & CONTROLLERNAME)

$.get( "http://localhost:PORT/api/CONTROLLERNAME/", function( data ) {
    //$( ".result" ).html( data );
    alert( "Get data received:" + data);
});

Side note: There are some pros/cons to consider when combining MVC and Web API in a project

WebAPI Help verification: http://localhost:PORT/help

Community
  • 1
  • 1
lko
  • 8,161
  • 9
  • 45
  • 62
  • @Iko i ve done everything that you wrote on the code but i ve an error when i run it . it gives me an error – ninjaXnado Dec 15 '14 at 13:20
  • 1
    Try searching for the error message. These steps were essentially what was required in the general case. – lko Jan 05 '15 at 13:24
  • 14
    "Order of the Global.asax.cs routes is critical" +1 – Jim Aho Sep 29 '15 at 20:01
  • I couldn't understand how to test if I added Web API correctly? What exactly should I write to the browser? I wrote `http://localhost:12345/api/Get/5` but I got an error. – jason Dec 12 '15 at 11:36
  • @JimAho, you are right, this must be written at right place. – Kundan Singh Chouhan Feb 29 '16 at 17:44
  • Instead of `GlobalConfiguration.Configuration.Formatters` it seems better to use `config.Formatters`. – Rudey Mar 27 '16 at 17:53
  • 3
    I was using the "old way" calling WebApiConfig.Register(GlobalConfiguration.configuration); and I could no longer debug. I would start debugging and it would never reach my controller functions. I changed to the "new way" GlobalConfiguration.Configure(WebApiConfig.Register); and the problem was fixed. – D. Kermott May 18 '16 at 21:52
  • Ruud Lenders (it seems better to use config.Formatters): Why? – netfed Jul 17 '16 at 16:54
  • Great write up..very helpful when adding a Web API controller to an existing MvC project – Matt Nov 15 '17 at 14:50
  • 1
    @jason, if you want to use Action name in URL just copy paste route after default one, give it a name and modify route template like this `"api/{controller}/{Action}/{id}"` – sairfan Sep 17 '18 at 17:13
  • While the accepted answer does a good job of answering the question literally, it does leave out how to secure the Web API controller. It will not simply inherit the security of the ASP.NET MVC web application. Of course, I say this for selfish reasons because I'm struggling to figure out how to secure my new Web API controller :( If I figure it out I will post it here as a comment. – Newclique Mar 14 '19 at 21:02
  • To rephrase a little, the answer leaves out how to secure the Web API controller with a bearer token (necessary for avoiding CSRF attacks on your APIs). – Newclique Mar 14 '19 at 21:37
  • Well, golly, it wasn't too hard after all. I made a new Web API project and took note of what VS 2017 did: Use NuGet to add Microsoft.Owin.Security.ActiveDirectory and add app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = tenantId, TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true }, }); to Startup.Auth.cs – Newclique Mar 14 '19 at 22:13