gpt4 book ai didi

c# - 查询参数路由约束

转载 作者:太空狗 更新时间:2023-10-30 00:24:48 25 4
gpt4 key购买 nike

我刚开始使用 ASP.NET Web API 2.1,但遇到了限制。使用属性路由,我可以执行以下操作:

[Route("item/{id:int}")]
public IHttpActionResult GetItem(int id)
{
...
}

URL /item/5 将被路由到此操作,但 URL /item/abc 不会,因为 int {id:int} 中的约束。

我尝试更改我的 URL,以便 id 参数与其约束一起出现在查询字符串中,尽管在文档中从未提及或演示过对查询参数使用路由约束。

[Route("item?{id:int}")]
public IHttpActionResult GetItem(int id)
{
...
}

如果我现在尝试运行,我会在 Application_Start 中的 Configure 方法调用中收到错误消息。

protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}

消息如下。

ArgumentException was unhandled by user code

The route template cannot start with a '/' or '~' character and it cannot contain a '?' character.

有两件事困扰着我。

首先,the section documenting Route Prefixes在 MSDN 上明确表示在路由模板的开头放置一个 ~ 字符是完全可以接受的。我试过了,它按照文档中的说明工作。

其次,如果不是这样,我如何在查询参数上放置路由约束?考虑以下内容,删除路由约束。

[Route("item")]
public IHttpActionResult GetItem(int id)
{
...
}

URL /item/5 将被路由到此操作,id 设置为 5 - 但 URL /item/abcid 设置为 0

有没有办法在查询参数上放置路由约束?

最佳答案

根据 http://attributerouting.net/#asp-net-web-api (†),这是不可能的:

"Beware! Due to integration issues with the Web API WebHost framework, the following features will not work: …

  • querystring parameter constraints, …"

†) 请注意,此答案是为以前版本的 Web API 编写的,其中属性路由是使用单独的 AttributeRouting.WebApi NuGet package 完成的。 .属性路由自此为incorporated into the Web API core .尽管如此,似乎仍然不支持开箱即用的查询字符串参数约束。

关于c# - 查询参数路由约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21589011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com