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

h7appiyu  于 2023-03-31  发布在  .NET
关注(0)|答案(1)|浏览(143)

假设我有一个汽车的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 }
             );

我得到“发现多个控制器类型”错误。
如何管理这样的路由?在某些时候,我想添加其他控制器以相同的方式寻址,例如BrakeController到baMap到汽车/车轮/{wheelId}/brake/* 等。
编辑:使用.net framework 4.7.2

qojgxg4l

qojgxg4l1#

你的url太复杂了,配置不可靠。最好使用属性路由,修复配置

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)
...

相关问题