2013-07-05 86 views
0

說我有以下操作;ASP.NET WebAPI路由問題

// api/products 
public IEnumerable<ProductDto> GetProducts() 
public ProductDto GetProduct(int id) 

// api/products/{productId}/covers 
public IEnumerable<CoverDto> GetCovers(int productId) 

什麼是創建一個快捷方式,使用「主」的產品路線的最好方法?api/products/master

我試着添加一個主控制器和路由上面,但我得到以下錯誤:

The parameters dictionary contains a null entry for parameter 'id' 
of non-nullable type 'System.Int32' for method 'ProductDto GetProduct(Int32)' 
in 'ProductsController'. An optional parameter must be a reference type, 
a nullable type, or be declared as an optional parameter. 

爲了解決這個問題,我已經試過更新普通產品路線到api/products/{id:int},但無濟於事。

我想結束以下;其中唯一的區別是,「主」產品將通過代碼,而不是一個ID

api/products 
api/products/1 
api/products/1/covers 
api/products/master 
api/products/master/covers 

回答

0

這些路線應該做的伎倆來獲得:

config.Routes.MapHttpRoute(
    name: "MasterAction", 
    routeTemplate: "api/{controller}/master/{action}", 
    defaults: new { action = "GetProduct", id = 999 } // or whatever your master id is 
); 

config.Routes.MapHttpRoute(
    name: "Action", 
    routeTemplate: "api/{controller}/{id}/{action}", 
    defaults: new { action = "GetProduct" } 
); 

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

你需要改變GetCovers方法的參數名稱從productIdid,或者您將需要添加一些定義爲{productId}的更多路由。

隨着「覆蓋」的路線,你要麼需要改變的URI是:

api/products/1/getcovers 
api/products/master/getcovers 

或者,如果你想保持的URI完好無損,你就需要改變你的操作方法看這樣

[HttpGet] 
public IEnumerable<CoverDto> Covers(int id) 
+0

謝謝,但就像我說的,「大師」的產品需要通過**產品代碼**,不是999號像你有獲得。這將意味着另一個控制器操作,但我不知道如何執行路線。 –

+0

我想我不知道你的產品代碼是什麼意思。什麼是產品代碼的例子? –