2015-11-04 148 views
3

根據命名約定,WebApi控制器操作名稱應爲Get(),Put()。 Post()等。但是告訴我,如果我有一個控制器作爲CustomerController,現在我想在它內部有兩個動作。一個是GetCustomerById(int id)另一個是GetCustomerByAge(int age)。這兩個動作都接受一個參數爲int。WebApi控制器操作命名約定

所以,如果我想使網址用戶友好像「API /客戶/」我也想跟着行動命名約定只喜歡獲取(INT ID)/獲取(INT年齡),如何我會做嗎?

+0

您正在使用哪個Web Api版本?如果您使用的是Web Api 2,那麼您可以使用Route屬性。 –

回答

6

如果您希望Web API來當路由查找動作的名稱,在App_Start文件夾改變WebApiConfig.cs類如下:

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

然後,你可以做一個GET請求

http://mysite/api/customer/GetCustomerById/1 

此外,我建議你學習下面的文章進行更深層次的理解:

Routing by Action Name

+3

這個答案具有誤導性,REST應該在HTTP方法中使用路徑和動詞中的名詞,即GET/api/customers/1。更多細節:https://martinfowler.com/articles/richardsonMaturityModel.html –

2

另一種方法是HTTP方法屬性。

通過使用HttpGet,HttpPut,HttpPost或HttpDelete屬性修飾操作方法,您可以顯式指定操作的HTTP方法,而不是使用HTTP方法的命名約定。

在下面的示例中,查找產品信息的方法被映射到GET請求:

public class ProductsController : ApiController 
{ 
    [HttpGet] 
    public Product FindProduct(id) {} 
} 

爲了允許一個操作多個HTTP方法,或允許HTTP方法比GET其他,PUT,POST和DELETE,使用AcceptVerbs屬性,該屬性採用HTTP方法的列表。

public class ProductsController : ApiController 
{ 
    [AcceptVerbs("GET", "HEAD")] 
    public Product FindProduct(id) { } 
}