【发布时间】:2014-02-05 21:34:35
【问题描述】:
我刚开始使用 ASP.NET Web API 2.1 并遇到了限制。使用属性路由,我可以做到以下几点:
[Route("item/{id:int}")]
public IHttpActionResult GetItem(int id)
{
...
}
URL /item/5 将被路由到此操作,但 URL /item/abc 不会,因为 {id:int} 中的 int 约束。
我尝试更改我的 URL,以便 id 参数及其约束在查询字符串中,尽管文档中从未提及或演示过对查询参数使用路由约束。
[Route("item?{id:int}")]
public IHttpActionResult GetItem(int id)
{
...
}
如果我现在尝试运行,我会在 Application_Start 中的 Configure 方法调用上收到错误消息。
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
消息如下。
ArgumentException 未被用户代码处理
路由模板不能以“/”或“~”字符开头,并且不能包含“?”字符。
有两件事困扰着我。
首先,MSDN 上的the section documenting Route Prefixes 明确表示,在路由模板的开头放置一个~ 字符是完全可以接受的。我试过了,它的工作原理与文档一致。
其次,如果不是这样,如何在查询参数上放置路由约束?考虑以下情况,移除路由约束。
[Route("item")]
public IHttpActionResult GetItem(int id)
{
...
}
URL /item/5 将被路由到此操作,id 设置为 5 - 但 URL /item/abc 也将路由到此操作,id 设置为 0。
有没有办法在查询参数上放置路由约束?
【问题讨论】:
-
我没试过,但是正则表达式。我使用了这篇文章:feedproxy.google.com/~r/TypeCastException/~3/0OVZG5c2bY0/…,看起来它允许约束。
-
@celerno 谢谢,但那是针对 MVC,而不是 Web API。
标签: c# asp.net asp.net-web-api-routing asp.net-web-api2