I am fiddeling with the new wep api in mvc 4 beta and adding some new api controllers to my existing mvc site. Problem is I can't name the web api controllers the same as my existing controllers. For now I have given them names like ProductApiController but that is not very restlike. What is a good strategy for namegiving of these new controllers when adding them to an existing mvc site?
The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. The same because it is MVC platform.
Before I illustrate how an ASP.NET MVC controller can be used as an API or a service, let's recap a few things: Web API controller implements actions that handle GET, POST, PUT and DELETE verbs. Web API framework automatically maps the incoming request to an action based on the incoming requests' HTTP verb.
If you have MVC project and you need to add Web API controller to this project, it can be done very easy. 1. Add Nuget package Microsoft.
MVC controllers inherited from Controller ; Web API controllers inherited from ApiController .
Problem is I can't name the web api controllers the same as my existing controllers.
You could have your API controllers with the same name as your existing controllers. Just put them in a different namespace to make the compiler happy.
Example:
namespace MyAppName.Controllers { public class ProductsController: Controller { public ActionResult Index() { var products = productsRepository.GetProducts(); return View(products); } } }
and the API controller:
namespace MyAppName.Controllers.Api { public class ProductsController: ApiController { public IEnumerable<Product> Get() { return productsRepository.GetProducts(); } } }
and then you have: /products
and /api/products
respectively to work with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With