2014-02-20 77 views
0

我使用WEB API創建了一個Web服務。ASP .NET Web API中的路由

我使用這個路由配置

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

而且我的解決方案包括兩個控制器(ProductControllerDetailController

所以,當我想調用指GetDetails方法WS(位於裏面DetailController)我必須使用這樣的URL:

http://localhost/api/Details/GetDetails/?id=4 

有沒有一種方法可以使用,對於相同的請求,這個URL取而代之的是:

http://localhost/api/Product/GetDetails/?id=4 

讓DetailController中的GetDetails方法?

回答

4

其實你的URL應該是:

http://localhost/api/Details/4 
http://localhost/api/Products/4 

和你的控制器:

public class DetailsController: ApiController 
{ 
    public HttpResponseMessage Get(int id) 
    { 
     ... 
    } 
} 

和:

public class ProductsController: ApiController 
{ 
    public HttpResponseMessage Get(int id) 
    { 
     ... 
    } 
} 

現在的REST。

+0

你能解釋一下使用查詢參數而不是url本身來表示資源(即'http:// localhost/api/Details/4')的原因。它似乎不是「RESTful」。 –

+0

你說得對。在這種情況下使用'/ {id}'更漂亮。但這並不意味着查詢字符串參數不是RESTful。通常當我有可選參數時,我將它們作爲查詢字符串參數傳遞。這通常在需要採用多個參數的GET請求中有意義。但我同意你的看法,標識資源的標識符在路徑部分中傳遞的更好。 –

+0

不,我瞭解查詢參數的用例。它看起來像是id(在這種情況下)是爲了獨特地表示資源。 –