2016-02-11 40 views
0

是否可以使用僅一條單一路由映射以下操作?WebAPI子資源路由映射保留默認行爲

public class SimpleDataController : ApiController 
{ 
    // GET /SimpleData 
    public List<MyObject> Get(){ return new List<MyObject>();}; 

    // GET /SimpleData/4 
    public MyObject Get(int objectId){ return new MyObject{Id = objectId);}; 

    // GET /SimpleData/4/ObjectsForId 
    public List<MySubObject> ObjectsForId(int objectId){ return new List<MySubObject>();}; 

    // GET /SimpleData/4/ObjectsForId/3 
    public MySubObject ObjectsForId(int objectId, int subObjectId){ return new MySubObject();}; 
} 

在我WebApiConfig.cs我已經添加以下代碼路線:

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

這適用於:

  • GET /SimpleData/4/ObjectsForIdGET /SimpleData/4/ObjectsForId/3

對於GET /SimpleData我得到以下錯誤:

The requested resource does not support http method 'GET'.

對於GET /SimpleData/4我得到:

Multiple actions were found that match the request: Get on type Controllers.SimpleDataController ObjectsForId on type Controllers.SimpleDataController

我已經嘗試設置默認爲action爲「獲取」,這會爲上面的例子中工作,但將失敗POSTPUTDELETE,因爲它也會檢查名爲'Get'的action。 有沒有我不知道的詭計?

我不想爲每個控制器創建新的映射。

回答

0

您需要使參數id也是可選的。否則,該參數始終是必需的,而GET/SimpleData路由將不起作用。

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