Adding a WebApi controller to an existing ASP.NET MVC application

So I’ve got an existing ASP.NET MVC5 application and need to add a REST api using WebApi.

  • Add a new Controller
  • Select Web API 2 Controller – Empty (or whatever your preference is)
  • Add you methods as normal
  • Open Global.asax.cs and near the start, for example after AreaRegistration but before the route configuration, add
    GlobalConfiguration.Configure(WebApiConfig.Register);
    

easy enough. The key is to not put the GlobalConfiguration as the last line in the Global.asax.cs as I did initially.

If we assume your controller was named AlbumsController, it might looks something like this

public class AlbumsController : ApiController
{
   // api/albums
   public IEnumerable<Album> GetAllAlbums()
   {
      // assuming albums is populated 
      // with a list of Album objects
      return albums;
   }
}

as per the comment, access to the API will be through url/api/albums, see WebApiConfig in App_Start for the configuration of this URL.