【问题标题】:Route to allow a parameter from both query string and default {id} template路由以允许来自查询字符串和默认 {id} 模板的参数
【发布时间】:2018-08-11 07:47:17
【问题描述】:

我的 ASP.Net Core WebAPI 控制器中有一个动作,它采用一个参数。我正在尝试将其配置为能够以下列形式调用它:

api/{controller}/{action}/{id}
api/{controller}/{action}?id={id}

我似乎无法正确路由,因为我只能制作一种表格来识别。 (简化的)操作签名如下所示:public ActionResult<string> Get(Guid id)。这些是我尝试过的路线:

  • [HttpGet("Get")] -- 映射到api/MyController/Get?id=...
  • [HttpGet("Get/{id}")] -- 映射到api/MyController/Get/...
  • 两者——映射到api/MyController/Get/...

如何配置我的操作以使用两种 URL 形式调用?

【问题讨论】:

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


    【解决方案1】:

    如果你想使用路由模板 您可以在 Startup.cs 中提供一个这样的配置方法:

    app.UseMvc(o =>
            {
                o.MapRoute("main", "{controller}/{action}/{id?}");
            });
    

    现在您可以同时使用这两个请求地址。

    如果你想使用属性路由你可以使用同样的方式:

    [HttpGet("Get/{id?}")]
    public async ValueTask<IActionResult> Get(
             Guid id)
        {
    
            return Ok(id);
        }
    

    【讨论】:

      【解决方案2】:

      使参数可选

      [Route("api/MyController")]
      public class MyController: Controller {
      
          //GET api/MyController/Get
          //GET api/MyController/Get/{285A477F-22A7-4691-AA51-08247FB93F7E}
          //GET api/MyController/Get?id={285A477F-22A7-4691-AA51-08247FB93F7E}
          [HttpGet("Get/{id:guid?}"
          public ActionResult<string> Get(Guid? id) {
      
              if(id == null)
                  return BadRequest();
      
              //...
          }    
      }
      

      然而,这意味着您需要对操作中的参数进行一些验证,以说明它可以作为 null 传入的事实,因为操作能够自行接受 api/MyController/Get

      参考Routing to controller actions in ASP.NET Core

      【讨论】:

      • 感谢您的回答。不幸的是,它在项目上无法正常工作。也就是说,我是否将id 参数设置为可选并不重要;当我使用?id= 调用操作时,模型绑定器不会绑定参数。在配置中定义路由模板也不起作用。我错过了什么吗?
      猜你喜欢
      • 1970-01-01
      • 2020-10-15
      • 2019-06-11
      • 2017-06-29
      • 2017-01-17
      • 1970-01-01
      • 2015-02-20
      • 2019-12-05
      • 1970-01-01
      相关资源
      最近更新 更多