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

Datetime:2016-08-23 04:37:37         Topic: ASP.NET MVC          Share        Original >>
Here to See The Original Article!!!

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

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.


Put your ads here, just $200 per month.