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?
See Question&Answers more detail:
os