【问题标题】:Properly handling nested resources in ASP.net MVC 4 WebApi routing正确处理 ASP.net MVC 4 Web Api 路由中的嵌套资源
【发布时间】:2013-07-05 16:25:50
【问题描述】:

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

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

这是我的配置:

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

这些是行动:

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

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

等等。

当我要处理嵌套资源时出现问题:

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

这是我对这些的配置:

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

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

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

我想听听以最 RESTful 的方式完成此任务的方法

【问题讨论】:

标签: rest asp.net-web-api


【解决方案1】:

Microsoft 正在添加属性路由以增加路由系统的灵活性。 在场景 3 中查看 their documentation

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

How to handle hierarchical routes in ASP.NET Web API?

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多