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?
Asked
Active
Viewed 1.0k times
1 Answers
54
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.

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
So then I can add a api subfolder in the controllers folder and add the api controllers there? – terjetyl Feb 19 '12 at 22:35
-
@TT., yes, it's a possibility. – Darin Dimitrov Feb 19 '12 at 22:36
-
2Or maybe an Area for the web api is more appropriate? – terjetyl Feb 19 '12 at 22:39
-
@TT., yeah whatever you feel comfortable with. – Darin Dimitrov Feb 19 '12 at 22:39
-
2FYI, I've had trouble getting this to work and haven't been able to pinpoint the issue. When I use jquery to `GET` `/api/products` the server returns a 301 with the new location at `/api/products/` which returns with a 404. With a clean new web api project I can get it to work, but once I start adding references from nuget/solution it breaks. – Brian Cauthon Mar 21 '12 at 20:56
-
How would you configure the routes for this design in the AreaRegistration class? I am unable to map to the controller in the API namespace. – Garry English Oct 01 '12 at 19:04