【问题标题】:How to identify the correct Get/Post method in webapi如何在 webapi 中识别正确的 Get/Post 方法
【发布时间】:2016-02-18 17:41:40
【问题描述】:
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。

【问题讨论】:

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


【解决方案1】:

您的代码将产生编译时错误,因为您有 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()};
}

【讨论】:

  • 感觉web api1不支持属性路由,无法添加RoutePrefix("api/products")
  • 然后将第二个参数添加到单个方法中,如答案第二部分所述。
  • 我实际上不想添加第二个参数。
  • 那么您需要更新路由定义以在路由模式中包含操作方法,或者为学生创建第二个控制器。
  • 是否可以使用不同的方法名称?你能给我看一个示例来更新你的路由定义以在路由模式中包含操作方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多