简体   繁体   English

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

[英]Properly handling nested resources in ASP.net MVC 4 WebApi routing

I'd like to provide REST API in this way: 我想以这种方式提供REST API:

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: 尝试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
}

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 我想通过最RESTful方法来实现这一目标

Microsoft is adding Attribute Routing to increase the flexibility of the routing system. Microsoft正在添加属性路由以增加路由系统的灵活性。 Have a look at their documentation on Scenario 3 查看有关场景3 的文档

There is also some answers on Stack Overflow like: Stack Overflow上也有一些答案,如:

How to handle hierarchical routes in ASP.NET Web API? 如何在ASP.NET Web API中处理分层路由?

There are solutions based on specifying route mappings but if you want more a more generic solution, this is by far the best solution I have seen related to this topic. 有基于指定路由映射的解决方案,但如果您想要更多更通用的解决方案, 是我见过的与此主题相关的最佳解决方案。 Of course, Web API 2 has attribute routing. 当然,Web API 2具有属性路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM