5

I just started using ASP.NET Web API 2.1 and have encountered a limitation. Using Attribute Routing, I can do the following:

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

The URL /item/5 will be routed to this action, but the URL /item/abc will not, because of the int constraint in {id:int}.

I tried changing my URL so that the id parameter was in the query string along with its constraint, despite the use of route constraints on query parameters never being mentioned or demonstrated in the documentation.

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

If I try to run now, I get an error on the Configure method call in Application_Start.

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

The message is as follows.

ArgumentException was unhandled by user code

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

Two things bother me about this.

First, the section documenting Route Prefixes on MSDN makes clear that placing a ~ character at the start of the route template is completely acceptable. I tried it, and it works as documented.

Second, if not like this, how can I place a route constraint on a query parameter? Consider the following, with the route constraint removed.

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

The URL /item/5 will be routed to this action, with id set to 5 - but so will the URL /item/abc, with id set to 0.

Is there no way to place a route constraint on a query parameter?

4

1 回答 1

10

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

"当心!由于与 Web API WebHost 框架的集成问题,以下功能将无法使用:...</p>

  • 查询字符串参数约束,……”

†)请注意,此答案是为以前版本的 Web API 编写的,其中属性路由是使用单独的AttributeRouting.WebApiNuGet 包完成的。属性路由已被合并到 Web API 核心中。尽管如此,似乎仍然不支持开箱即用的查询字符串参数约束。

于 2014-02-05T21:46:51.490 回答