如何在webapi中识别正确的Get / Post方法

时间:2016-02-18 17:41:40

标签: asp.net-mvc-4 asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

I want to implement two get methods based on different id in web api service
eg:
// GET api/Data/5

 public List<Data> GetMyDatas(int id)
// GET api/Data/15
 public List<Data> GetMyDatas(int studid).

如果我从我的mvc控制器调用它,它将如何识别它被调用的get方法。有没有办法说出来。我有一个mvc项目和另一个mvc webapi1项目。我从我的mvc项目中调用webmethod。 VS 2010,MVC 4,Web API 1。

1 个答案:

答案 0 :(得分:2)

您的代码将产生编译时错误,因为您有两个具有相同名称的方法。

你应该做的是,创建一个2个单独的方法并使用不同的url模式。

启用属性路由后,

[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
    public List<string> GetMyDatas(int id)
    {
        return new List<string> {"product 1", "value2", id.ToString()};
    }

    [Route("Students/{studId}")]
    public List<string> GetStudentDatas(int studid)
    {
        return new List<string> { "student", "Students", studid.ToString() };
    }
}

第一种方法可以像yourSite/api/products/3一样访问,第二种方法可以像yourSite/api/products/Students/3一样访问,其中3可以用有效数字替换

另一种选择是在单一操作方法中添加第二个参数,并根据参数确定要返回的数据。

public List<string> GetMyDatas(int id,string mode="")
{
    //based on the mode value, return different data.
    return new List<string> {"product 1", "value2", id.ToString()};
}