Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mix web api controllers and site controllers

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?

like image 500
terjetyl Avatar asked Feb 19 '12 21:02

terjetyl


People also ask

What is difference between controller and API controller?

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.

Can I use MVC controller as Web API?

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.

Can I add API controller to MVC project?

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.

What is the base controller for all Web API controller to inherit from?

MVC controllers inherited from Controller ; Web API controllers inherited from ApiController .


1 Answers

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.

like image 132
Darin Dimitrov Avatar answered Oct 15 '22 03:10

Darin Dimitrov