2013-07-05 14 views
10

をルーティングASP.net MVC 4 WEBAPIにネストされたリソースを扱う:が正しく、私はこのように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 
} 

これは当然のことながら、同じ署名。

私は

+0

これはhttp://stackoverflow.com/q/10783946/326110とhttp://stackoverflow.com/questions/9594671/nested-resources-in-asp-net-mvc-4-webapiの複製のようです/ 16094056#16094056 –

答えて

5

マイクロソフトは、ルーティングシステムの柔軟性を高めるためにルーティング属性を追加して、ほとんどのRESTfulなアプローチでこれを達成するための方法から聞きたいと思います。以下のようなスタックオーバーフロー上のいくつかの回答もあり

シナリオ3に が their documentationを見てください:

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

2

が、そこルートマッピングを指定するに基づくソリューションがありますが、あなたは、より多くの一般的な解決策が必要な場合はthisは私がこのトピックに関連して見てきた最良の解決策です。もちろん、Web API 2には属性ルーティングがあります。

関連する問題