参数绑定到ASP.NET MVC Core中的路由或查询字符串 [英] Parameter binding to either route or querystring in ASP.NET MVC Core

查看:59
本文介绍了参数绑定到ASP.NET MVC Core中的路由或查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将ASP.NET MVC(.NET Framework)Web应用程序迁移到ASP.NET MVC Core 3.1.该应用程序是公司内部的.我们正借此机会清理一些API路由,使它们更具RESTful风格,例如:/api/Values?id = 1 /api/Values/1 .但是,并非所有其他应用程序都能在该应用程序投入生产时进行适当的更改,因此我们希望能够同时支持这两种URL格式.这可能吗?我的路由设置如下:

I am migrating a ASP.NET MVC (.NET Framework) web application to ASP.NET MVC Core 3.1. This application is internal to the company. We are taking the opportunity to clean up some of the API routing to make them more RESTful, for example: /api/Values?id=1/api/Values/1. However, not all of our other applications will be able to make the appropriate changes at the time when this application goes to production, so we want to be able to support both URL formats simultaneously. Is this possible? My routing setup looks like:

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.Select().Expand().Filter().OrderBy().Count().MaxTop(null);
    endpoints.EnableDependencyInjection();
    endpoints.MapODataRoute("ODataRoute", "odata", GetEdmModel());
});

我的控制器如下:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : Controller
{
    // constructor and dependency injection omitted

    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Get(int id)
    {
        // method logic omitted
    }
}

使用上面的代码,/api/Values/1 可以正常工作,但是查询字符串?id = 1 的结果为404.如果我将属性更改为只需 [HttpGet] 即可,查询字符串有效,但RESTful版本无效.到目前为止,这是我尝试过的:

With the above code, /api/Values/1 works fine, but the query string ?id=1 results in a 404. If I change the attribute to just [HttpGet] then the query string works, but the RESTful version doesn't. Here's what I've tried so far:

  • [HttpGet("{id}")) + [FromQuery] – REST:404,QS:405(不允许使用方法)
  • [HttpGet] + [FromQuery] [FromRoute] – REST:404,QS:200
  • [HttpGet("{id?}'')) – REST:200,QS:404
  • [HttpGet("{id}")] + [FromQuery] – REST: 404, QS: 405 (method not allowed)
  • [HttpGet] + [FromQuery] [FromRoute] – REST: 404, QS: 200
  • [HttpGet("{id?}")] only – REST: 200, QS: 404

这有可能吗?谢谢.

推荐答案

要实现此要求,您可以尝试定义达到相同操作的多个路由,如下所示.

To achieve the requirement, you can try to define multiple routes that reach the same action, like below.

[HttpGet]
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Get(int id)
{
    if (Request.Query.TryGetValue("id",out StringValues qs_id))
    {
        int.TryParse(qs_id.FirstOrDefault(), out id);
    }

    //...

    // method logic omitted

    //for testing purpose 

    return Ok($"id is {id}");
}

测试结果

更新:

如果可能,您还可以尝试实施和使用URL重写规则来实现它.

If possible, you can also try to implement and use URL Rewrite Rule(s) to achieve it.

<rule name="id qs rule">
    <match url="api/values" />
    <conditions>
          <add input="{PATH_INFO}" pattern="api/values$" />
          <add input="{QUERY_STRING}" pattern="id=([0-9]+)" />
    </conditions>
    <action type="Rewrite" url="api/values/{C:1}/" appendQueryString="false" />
</rule>

测试结果

这篇关于参数绑定到ASP.NET MVC Core中的路由或查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆