2012-02-17 41 views
3

我有兩個方法,這樣的ASP.NET Web API結合方法

public class ProductController : ApiController 
{ 
    public Product GetProductById(int id) 
    { 
     var product = ... //get product 
     return product; 
    } 

    public Product GetProduct(int id) 
    { 
     var product = ... //get product 
     return product; 
    } 
} 

當我打電話網址:GET http://localhost/api/product/1。我想調用第一個方法,而不是第二個方法。
我該怎麼做?

回答

4

您需要唯一的URI。你可以修改你的路線,得到這樣的:

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

);

現在,您可以訪問您的API是這樣的:

http://localhost/api/product/GetProductById/1

http://localhost/api/product/GetProduct/1

我寫了一個小introduction to ASP.NET Web API其中顯示了一些分歧,WCF的Web API。

您還可以添加默認操作,例如,在一個列表的所有產品,所以你可以做這樣的事情:

http://localhost/api/product/ // returns the list without specifying the method 

,另一種是通過這種方式調用

http://localhost/api/product/byid/1 // returns the list without specifying the method 

我是有一個ProductsController的和ProductController的是什麼。 ProductsController負責T集合上的操作(get all),ProductController負責T上的操作(如獲取特定的一個)。

+0

這樣,它不是REST,它是RPC。我在尋找一個屬性,比如[NeverBind] ...但它們還沒有存在,我們可以使用這個屬性來標記一個方法,當我們不想將它綁定到一個URI。 – dohaivu 2012-02-17 12:39:39

+0

更新了我的評論。 – 2012-02-17 12:40:43

+0

當我問這個問題時,我想知道我是否有一個以Get爲前綴的方法,ASP.NET Web API如何綁定它們,我希望它是REST方式,而不是RPC方式。我谷歌,但沒有回答 – dohaivu 2012-02-17 12:46:12