سؤال

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 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 }
);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top