正确处理ASP.net MVC 4 WebApi路由中的嵌套资源

mar*_*cho 12 rest asp.net-web-api

我想以这种方式提供REST API:

GET /api/devices
POST /api/devices
PUT /api/devices/1
DELETE /api/devices/1
Run Code Online (Sandbox Code Playgroud)

这是我的配置:

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

这些是行动:

public IEnumerable<Device> Get()
{
//return all devices
}

public Devices Get(id)
{
//return a specific devices
}
Run Code Online (Sandbox Code Playgroud)

等等.

当我想处理嵌套资源时,会出现此问题:

GET /api/devices/1/readings
POST /api/devices/1/readings
GET /api/devices/1/readings/1
PUT /api/devices/1/readings/1
DELETE /api/devices/1/readings/1
Run Code Online (Sandbox Code Playgroud)

这是我对这些的皈依:

config.Routes.MapHttpRoute(
    name: "NestedApi",
    routeTemplate: "api/{controller}/{parentResourceId}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

尝试GET和POST到嵌套资源时出现问题:

[HttpGet]
public String Readings(int parentResourceId)
{
   //return a list of readings for the device
}

[HttpPost]
public String Readings(int parentResourceId)
{
    //create and return the id of a reading for the device
}
Run Code Online (Sandbox Code Playgroud)

当然,这是失败的,因为有两个具有相同签名的操作.

我想通过最RESTful方法来实现这一目标

小智 6

Microsoft正在添加属性路由以增加路由系统的灵活性.查看有关场景3 的文档

Stack Overflow上还有一些答案,如:

如何在ASP.NET Web API中处理分层路由?