简体   繁体   English

ASP.NET MVC 4 ApiController和普通控制器路由

[英]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. 我有一个项目,仅用于API请求到我们的应用程序,我们正在使用ASP.NET MVC 4项目。 We have some Controllers that derive from the ApiController and others that derive from the normal Controller class. 我们有一些从ApiController派生的控制器和从普通Controller类派生的其他控制器。 The issue is that I don't want to have the default routing for the ApiControllers of api/XXXXX/ . 问题是我不想拥有api/XXXXX/的ApiControllers的默认路由。 I want the same routing to be used for the ApiControllers as the non-Api Controllers, namely {controller}/{action}/{id} . 我希望将相同的路由用作ApiControllers作为非Api控制器,即{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. 这将使我的ApiControllers可以使用普通的{controller}/{action}路由进行访问,但是“普通”控制器不再可访问。 If I get rid of the MapHttpRoute the opposite happens. 如果我摆脱了MapHttpRoute发生相反的情况。

Is there any way to have ApiControllers and "normal" Controllers accessible via the same url routes? 有没有办法通过相同的URL路由访问ApiControllers和“普通”控制器?

The only way this can be done from what I can see is to explicitly name each API controller. 从我能看到的唯一方法就是明确命名每个API控制器。 Below I have a SomeApiController class. 下面我有一个SomeApiController类。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM