【问题标题】:How to route to api/values?id=1&type=2如何路由到 api/values?id=1&type=2
【发布时间】:2019-08-23 02:55:16
【问题描述】:

我正在使用 .net core 2.1 web api。我有一个 ValuesController 和路由,例如 api/values/5 & api/values/ 工作正常。但现在我想路由到类似 api/values?id=5&type=2 的东西。有可能有这样的路线吗?

我搜索了 stackoverflow 和其他网站,但没有找到方法。我尝试使用下面的代码,但不起作用。

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value" + id;
        }

        [HttpGet]
        public ActionResult<string> Get(int id, int type)
        {
            return "value: " + id + "with type: " + type;
        }
    }

我想路由为 api/values?id=5&type=2 或 api/values/id=5&type=2

【问题讨论】:

    标签: asp.net-core routes asp.net-core-webapi asp.net-core-2.1


    【解决方案1】:

    尝试以下更改:

        [HttpGet]
        [Route("id={id}&type={type}")]   // GET api/values/id=5&type=2
        public ActionResult<string> Get(int id, int type)
        {
            return "value: " + id + "with type: " + type;
        }
    

    【讨论】:

      【解决方案2】:

      您不能通过查询字符串来区分路线。您应该合并两个 'Get' 方法并调用 api/values?id=5&amp;type=2

      [HttpGet]
      public ActionResult Get(int id, int type)
      {
      
          if (id == 0 && type == 0)
          {
              return Ok(new string[] { "value1", "value2" });
          }
          else
          {
              return Ok("value: " + id + " with type: " + type);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-09
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多