2012-02-17 65 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