Home > Mobile >  APS.NET MVC request routing using query parameter names
APS.NET MVC request routing using query parameter names

Time:12-23

I'm trying to understand attribute routing in ASP.NET MVC. I understand how routing matches on url elements, but not query parameters.

For example, say I have a rest-style book lookup service that can match on title or ISBN. I want to be able to do something like GET /book?title=Middlemarch or GET /book?isbn=978-3-16-148410-0 to retrieve book details.

How do I specify [Route] attributes for this? I can write:

[HttpGet]
[Route("book/{title}")]
public async Task<IActionResult> LookupTitle(string title)

but as far as I can tell this also matches /book/Middlematch and /book/978-3-16-148410-0. If I also have an ISBN lookup endpoint with [Route("book/{isbn}")] then the routing engine won't be able to disambiguate the two endpoints.

So how do I distinguish endpoints by query parameter name?

CodePudding user response:

The following Route() attribute will meet your requirements:

[HttpGet] 
// /book?title=Middlemarch 
// /book?isbn=978-3-16-148410-0
// /book?title=Middlemarch&isbn=978-3-16-148410-0 
[Route("book/")] 
public IActionResult LookupTitle(string isbn, string title)
{
    if (isbn != null) { /* TODO */ }
    if (title != null) { /* TODO */ }

    return View();
}

When the ASP.NET MVC parser does not find any matching parameters in the route pattern it trying to interpret these as query parameters.

  • Related