Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c# - Query parameter route constraints

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to http://attributerouting.net/#asp-net-web-api (†), this is not possible:

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

  • querystring parameter constraints, …"

†) Note that this answer was written for a previous version of Web API where attribute routing was done using a separate AttributeRouting.WebApi NuGet package. Attribute routing has since been incorporated into the Web API core. Nevertheless, it appears that constraints on query string parameters are still not supported out of the box.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...