【问题标题】:WebAPI Controller GetAll or Get some IdWebAPI 控制器 GetAll 或获取一些 Id
【发布时间】:2017-07-25 21:52:09
【问题描述】:

我有一个这样的控制器

[Route("api/Foo/MyController/{id}")]
public IHttpActionResult Get(int id)
{
   //Code code
   foo(id); // Foo accept Int or Null
}

这确实有效,如果调用 api/Foo/MyController/1,但我需要调用 api/Foo/MyController 像“GetAll”这样的参数 id 现在是null 和控制器中的东西全部返回,怎么去那里?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api2 asp.net-web-api-routing


    【解决方案1】:

    你可以添加一个新的方法和路由:

    [Route("api/Foo/MyController")]
    public IHttpActionResult Get()
    {
       //Code code
    }
    

    编辑:要重用相同的方法,您可以使用可选参数:

        [Route("api/Foo/MyController/{id}")]
        public IHttpActionResult Get(int? id)
        {
            if (id.HasValue)
            {
               // get by id
            } 
            else
            {
               // get all
            }
        }
    

    【讨论】:

    • +1 为答案。当然,但我认为,存在某种方式将其包含在同一个 Get 中,而不是另一个 Get。问候
    • @nimeshjm 在这里绝对正确。您可以使用默认值并将所有内容组合到一个 API 中,但将两者分开更为常见(特别是因为检索数据的代码块会有所不同)。
    【解决方案2】:

    为什么没有 2 个单独的方法:

    [Route("api/Foo/")]
    public IHttpActionResult GetAll()
    {
       // code
    }
    
    [Route("api/Foo/{id}")]
    public IHttpActionResult GetById(int id)
    {
       // code
    }
    

    为了清楚起见(可读性、可维护性、可支持性)。

    【讨论】:

      【解决方案3】:

      你也可以做一个可选参数:

      [Route("api/Foo/MyController/{id}")]
      public IHttpActionResult Get(int? id = null)
      {
          IQueryable foo = GetData();
          if (id.HasValue)
          {
              foo = foo.Where(e => e.Id == id.Value);
          }
          //...
      }
      

      【讨论】:

        猜你喜欢
        • 2014-10-08
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-07
        相关资源
        最近更新 更多