Mixing Web Api and ASP.Net MVC Pages in One Project

asp.net Mvc-4

asp.net Mvc-4 Problem Overview


How do I mix Web API and ASP.Net MVC pages in one project?

For instance, I have model User. I would like, within the same project, to have an ApiController that would respond to all the HTTP verbs for managing the User entities, and at the same time have a Controller that would return the appropriate strongly-typed Views depending on the Action requested.

I can't name both controllers UserController. What is the best way around this? Should I name one UserApiController and the other UserController? Any other suggestions?

asp.net Mvc-4 Solutions


Solution 1 - asp.net Mvc-4

You can put them in separate namespaces, e.g MyApp.Controllers.UsersController and MyApp.Controllers.WebAPI.UsersController.

This would let you expose similar URI routes in MVC and WebAPI, eg:

/users/1      << MVC view
/api/users/1  << Web API

Solution 2 - asp.net Mvc-4

I haven't changed the namespaces, the only thing that I had to do was register WebApi first, and then MVC route

//First register WebApi router
GlobalConfiguration.Configure(WebApiConfig.Register);
//and register Default MVC Route after
RouteConfig.RegisterRoutes(RouteTable.Routes);

and everything works great!

Solution 3 - asp.net Mvc-4

The WebApi implementation should be added as a separate Area in the MVC application. It is a natural fit. Doing this gives you the separate namespace that Mike Wasson recommended, plus it gives you a natural way to set up the /api routing. You get a separate model folder

Additionally, it is very specifically separated from the rest of the project. If requirements in the future are ever such that you need to separate the api implementation into a separate project, having the api implementation isolated to a separate area makes that breaking it out a lot easier.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonas ArcangelView Question on Stackoverflow
Solution 1 - asp.net Mvc-4Mike WassonView Answer on Stackoverflow
Solution 2 - asp.net Mvc-4AlexView Answer on Stackoverflow
Solution 3 - asp.net Mvc-4CleverPatrickView Answer on Stackoverflow