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?
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.
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.
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.
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 }
);
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