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

前端 未结 3 717
春和景丽
春和景丽 2020-11-28 10:20

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 wou

相关标签:
3条回答
  • 2020-11-28 10:42

    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!

    0 讨论(0)
  • 2020-11-28 11:06

    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
    
    0 讨论(0)
  • 2020-11-28 11:06

    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.

    0 讨论(0)
提交回复
热议问题