Posted on

add Web API to an mvc site

Install the Web API Client Libraries

Use NuGet Package Manager to install the Web API Client Libraries package :

  • Microsoft.AspNet.WebApi.Client
  • Microsoft.AspNet.WebApi.Core
  • Microsoft.AspNet.WebApi.WebHost

Define a Web API Routing Configuration

Add App_Start\WebApiConfig.cs

using System.Web.Http;

class WebApiConfig
    public static void Register(HttpConfiguration configuration)
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }

Register the WebAPI Routing Configuration

If you added a new WebApiConfig.cs file, you need to register that on your Web Application’s main configuration class.

Import namespace System.Web.Http in Global.asax.cs.

Add this line before the registration of your classic routing

//api routing (before)
//existing normal route

Create a sample Web API Controller

Create a new controller

using System;
using System.Web.Http;

namespace MySite.Controllers
    public class SampleController : ApiController
       public String Test()
         return "Hello World!";

Based on the api routing you should call this method in your browser using


with this result

<string xmlns=””>Hello World!</string>