Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 ApiController and Normal Controller Routes

I have a project that is used solely for API requests into our app and we are using an ASP.NET MVC 4 project. We have some Controllers that derive from the ApiController and others that derive from the normal Controller class. The issue is that I don't want to have the default routing for the ApiControllers of api/XXXXX/. I want the same routing to be used for the ApiControllers as the non-Api Controllers, namely {controller}/{action}/{id}. I tried adding the following routes

routes.MapHttpRoute(
    name: "Api",
    routeTemplate: "{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

This will make it so that my ApiControllers are accessible using the normal {controller}/{action} routing but "normal" Controllers are no longer accessible. If I get rid of the MapHttpRoute the opposite happens.

Is there any way to have ApiControllers and "normal" Controllers accessible via the same url routes?

like image 694
Nick Olsen Avatar asked Aug 24 '13 16:08

Nick Olsen


People also ask

What is the difference between ApiController and MVC 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 we have multiple routes in MVC?

Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.

What happens when you add the ApiController attribute to a controller in asp net core?

The [ApiController] attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors: Attribute routing requirement. Automatic HTTP 400 responses. Binding source parameter inference.


1 Answers

The only way this can be done from what I can see is to explicitly name each API controller. Below I have a SomeApiController class.

routes.MapHttpRoute(
    name: "SomeApiController",
    routeTemplate: "SomeApi/{action}/{id}",
    defaults: new { controller = "SomeApi", id = RouteParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
like image 140
Nick Olsen Avatar answered Sep 21 '22 21:09

Nick Olsen