asp.net REST API在另一个控制器路由中嵌入到一个控制器的路由



假设我有一个汽车的API:我有一个WheelsController和一个WheelNutsController。

我希望能够访问来自WheelController的方法:

GET /car/wheels/ - gets all the wheels
GET /car/wheels/{wheelId} - gets a single wheel, 
DELETE /car/wheels/{wheelId} - remove a wheel
GET /car/wheels/{wheelId}/speed - gets a speed of a single wheel

但是以同样的方式,我希望能够从WheelNutController

访问WheelNust方法
GET /car/wheels/{wheelId}/wheelnuts - gets a list of wheel nuts associated with a wheel {wheelId} 
POST /car/wheels/{wheelId}/wheelnuts/{nutId}/tighten - some other method to work on a WheelNut.

如果我做这样的路由:

config.Routes.MapHttpRoute(
"SettlementSubAPI",
"api/Wheels/{wheelId}/{controller}/{id}",
new { id = RouteParameter.Optional , controller  = "WheelNuts"}
);
config.Routes.MapHttpRoute(
"3wayroute",
"api/{controller}/{id}/{AttributeName}",
new { AttributeName = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
"DefaultAPI",
"api/{controller}/{id}",
new {  id = RouteParameter.Optional }
);

i get "找到多个控制器类型"错误。

如何管理这样的路由?在某些时候,我想添加其他控制器以同样的方式寻址,例如BrakeController映射到car/wheels/{wheelId}/brake/*等。

编辑:使用。net framework 4.7.2

您的url太复杂,配置无法使其可靠。最好使用属性路由,修复config

config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });

和添加属性到动作

[HttpPost("~/car/wheels/{wheelId}/WheelNuts/{nutId}/Tighten")] 
public IActionResult WheelNutsTighten(int wheelId, int nutId)
...

相关内容

  • 没有找到相关文章

最新更新