13

I'd like to provide REST API in this way:

GET /api/devices
POST /api/devices
PUT /api/devices/1
DELETE /api/devices/1

This is my configuration:

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

And these are the actions:

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

public Devices Get(id)
{
//return a specific devices
}

and so on.

The issue appears when I want to handle nested resources:

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

This is my configration for these:

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

The issue shows up when trying to GET and POST to the nested resource:

[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
}

This is, of course, failing because there are two actions with the same signature.

I'd like to hear from a way of accomplishing this with the most RESTful approach

4

2 回答 2

7

Microsoft 正在添加属性路由以增加路由系统的灵活性。看看他们关于场景 3的文档

Stack Overflow 上也有一些答案,例如:

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

于 2013-07-05T17:28:20.390 回答
2

有基于指定路由映射的解决方案,但如果您想要更通用的解决方案,是迄今为止我见过的与该主题相关的最佳解决方案。当然,Web API 2 有属性路由。

于 2013-07-05T17:29:05.443 回答