13

この方法で 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
}

もちろん、同じ署名を持つ 2 つのアクションがあるため、これは失敗しています。

最もRESTfulなアプローチでこれを達成する方法について聞きたいです

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 に答える