ASP.NET MVC 4 ApiController和正常控制器路由 [英] ASP.NET MVC 4 ApiController and Normal Controller Routes
问题描述
我有一个仅用于API请求到我们的应用程序的一个项目,我们使用的是ASP.NET MVC 4项目。我们有一些控制器从ApiController获得和其他人从正常的控制器类派生。问题是,我不希望有的ApiControllers默认路由API / XXXXX /
。我想用于ApiControllers作为非API控制器,相同的路由,即 {控制器} / {行动} / {ID}
。我尝试添加以下路线
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 }
);
这将让这个我ApiControllers是使用正常 {}控制器访问/ {行动}
路由,而是正常的控制器将不再访问。如果我摆脱 MapHttpRoute
情况正好相反。
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.
有什么办法让ApiControllers和正常的控制器通过相同的URL访问路线?
Is there any way to have ApiControllers and "normal" Controllers accessible via the same url routes?
推荐答案
这可以从我所看到的是明确地命名每个API控制器来实现的唯一途径。下面我有一个SomeApiController类。
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 }
);
这篇关于ASP.NET MVC 4 ApiController和正常控制器路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!