【问题标题】:MVC Attribute Routing with query parameter not working带有查询参数的 MVC 属性路由不起作用
【发布时间】:2021-12-12 13:51:30
【问题描述】:

我正在尝试将我的 UI 项目和 WebAPI 项目合二为一,以使其更易于维护,但是我收到以下路由错误:

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:64182/api/v1/business?id=101'.",
    "MessageDetail": "No type was found that matches the controller named 'api'."
}

我已在方法上添加了属性路由以使其工作,但它仅适用于以下 url:

MVC 动作:

[HttpGet, Route("api/v1/business/{id:int}")]
public IHttpActionResult Get([FromUri]int? id)
{
....
}

http://localhost:64182/api/v1/business/101

预期的 url 签名不能更改,它仍应使用查询参数:

http://localhost:64182/api/v1/business?id=101

在 Route 属性中,我不能添加问号,因为它是不允许的。

该系统已被许多用户使用,很遗憾我无法更改签名,否则会破坏他们的系统。

我怎样才能让它工作,或者我可以使用什么路由模板来包含查询参数?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core asp.net-web-api routes


    【解决方案1】:

    我认为 [FromUri] 属性已被弃用。尝试使用 [FromRoute]。另外,我将从控制器类构建我的路由。

    以下是http://localhost:64182/api/v1/business/101

    [Route("api/v1/[controller]")]
    [ApiController]
    public class Business : ControllerBase
    {
    
        [HttpGet("/{id:int}")]
        public async Task<ActionResult<YourBusinessDto>> Get([FromRoute] int id)
        {
            //Your code to get your business dto here.
        }
    }
    

    以下是http://localhost:64182/api/v1/business?id=101

    [Route("api/v1/[controller]")]
    [ApiController]
    public class Business : ControllerBase
    {
    
        [HttpGet]
        public async Task<ActionResult<YourBusinessDto>> Get([FromQuery] int id)
        {
            //Your code to get your business dto here.
        }
    }
    

    【讨论】:

      【解决方案2】:

      在我们的订单集合中,每个订单都有一个唯一的标识符。我们可以去集合并通过“id”请求它。典型的 RESTful 最佳实践,这可以通过它的路由来检索,例如“api/orders/1”

      //api/orders/1
         [HttpGet("api/orders/{id}")]
                  public string test1([FromRoute]int id)
                  {
                      return "test1";
                  }
      

      此属性将指示 ASP.NET Core 框架将此操作视为 HTTP GET 动词的处理程序并处理路由。我们提供端点模板作为属性参数。此模板用作框架将用于匹配传入请求的路由。在这个模板中,{id}​​​​的值对应于路由部分作为“id”参数。 FromRoute 属性告诉框架在路由(URL)中查找“id”值并将其作为 id 参数提供。

      此外,我们可以很容易地编写它来使用 FromQuery 属性。然后,这会指示框架使用“标识符”名称和相应的整数值来预测查询字符串。然后将该值作为 id 参数传递给操作。其他一切都一样。

      不过,最常用的方法是前面提到的 FromRoute 用法——标识符是 URI 的一部分

      //api/orders?id=1
          [HttpGet("api/v1")]
                  public string test2([FromQuery]int id)
                  {
                      return "test2";
                  }
      

      另外,更多属性使用可以参考这篇详细文章,可能对你有帮助:

      https://www.dotnetcurry.com/aspnet/1390/aspnet-core-web-api-attributes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-14
        • 2017-07-14
        • 2019-12-02
        • 2017-12-20
        • 2016-01-26
        相关资源
        最近更新 更多