如何使用 [HttpGetAttribute] 路由,包括 AspNet.Core WebApi 应用程序中的查询字符串?

How to route using [HttpGetAttribute] including the query strings in AspNet.Core WebApi application?

我有以下路由,适用于调用 /api/demo/info/34.

[Route("api/demo")]
public class Demo : Controller
{
    [HttpGet("Info/{x}")]
    public JsonResult GetInfos(string x) { ... }
}

现在,我想将查询字符串传递给 select ID,如下所示:/api/demo/info?x=34。我应该如何重新表述该属性?

当我尝试输入 [HttpGet("Info?x={x}")] 时,错误消息说问号在那里无效。我想通过属性方法解决它,默认映射的路由不是一个选项。

您需要做的就是将您的属性声明为:

[HttpGet("Info")]

同时保持方法的签名为 GetInfos(string x)。在 GET 路由中,WebAPI 从签名中获取所有参数,路由中不存在的参数可以作为查询字符串参数传递,只要查询字符串中的名称与参数名称匹配即可。

只需从路由中删除参数,框架就会根据操作的参数对其进行解释。

[Route("api/demo")]
public class Demo : Controller {
    //GET api/demo/info?x=34
    [HttpGet("Info")]
    public JsonResult GetInfos(string x) { ... }
}