Can I have both a Controller and an ApiController for the same thing?

眉间皱痕 提交于 2019-11-30 22:07:42

问题


I've just started to use the VS 2012 RC, and I'm creating an ASP.NET MVC 4 web application in which I plan to provide both an HTML-based user interface and a WebApi-based programming interface.

For my HTML website, I have a controller and view for each of my models (MVC!), and the routing works "by convention" so that, for example, the URL /client hooks up to my ClientController. My ClientController derives from Controller.

For my API, I will create new controllers that derive from ApiController. I naturally want my API URLs to be similar to my HTML URLs, so I'd like the client info to be available at /api/client. However, with the by-convention routing, that would suggest that I need an ApiController named ClientController. And I already have a ClientController class.

How do I deal with this? Do I need custom routing? Do I put the API classes in different namespace so that I can give them the same name?

Update: this question seems to suggest that a different namespace for my API controllers is all I need: Mix web api controllers and site controllers


回答1:


All it requires is for the controller classes to be in a different namespace, and all is well.

Using MVC areas would also work (as suggested in gordonml's comment), but this effectively puts the controllers in different namespaces, so it's a more formal way of achieving the same result.




回答2:


You may take a look at the following blog post which illustrates how an Api controller could serve Razor views as well. Basically he uses the RazorEngine to parse the Razor view end serve it.




回答3:


For anyone looking for step by step guidance on how to do this on WebApi project:

  1. Create two folders / namespaces, namely: ControllersApi and ControllersWeb
  2. Right click on ControllersWeb and go Add -> Controller and select MVC 5 Controller - Empty. This will add all other dependencies if you didn't have them in your WebApi project.
  3. Your RouteConfig will now register those classes that inherit from Controller base class. You'll likely need to add link to default Controller, by editing defaults to say: defaults: new { action = "Index", controller = "Home", id = UrlParameter.Optional }

That's it, you can now run site and use both API and Web controllers.



来源:https://stackoverflow.com/questions/11564922/can-i-have-both-a-controller-and-an-apicontroller-for-the-same-thing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!