ASP.NET MVC 4 ApiController and Normal Controller

2019-02-26 01:21发布

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?

1条回答
祖国的老花朵
2楼-- · 2019-02-26 01:56

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 }
);
查看更多
登录 后发表回答