Search code examples
asp.net-web-apiasp.net-coreasp.net-web-api-routing

Url.Link() not generating proper link with querystring


I'm creating an ASP.NET Core WebAPI that has a route with an optional parameter. In the return result I am embedding links to "previous" and "next" pages. I'm using Url.Link() to generate these links, but the link created is not generating a proper URL.

Example code:

  [HttpGet("{page:int?}", Name = "GetResultsRoute")]
  public IActionResult GetResults([FromQuery]int page = 0)
  {
     ...
     var prevUrl = Url.Link("GetResultsRoute", new { page = page - 1 });
     var nextUrl = Url.Link("GetResultsRoute", new { page = page + 1 });
     ...

The URL generated will be something like:

http://localhost:65061/api/results/1

What I want is:

http://localhost:65061/api/results?page=1

What am I doing wrong here?


Solution

  • I think you are doing everything right here. It just MVC is able to match your [page] value in Url.Link to the route constraint HttpGet("{page:int?}", thus appending it as a part of the URL path, e.g. results/1 From the docs - Ambient values that don't match a parameter are ignored, and ambient values are also ignored when an explicitly-provided value overrides it, going from left to right in the URL. Values that are explicitly provided but which don't match anything are added to the query string. In your case,

    var prevUrl = Url.Link("GetResultsRoute", new { pageX = page - 1 });
    

    would result in

    http://localhost:65061/api/results?pageX=1
    

    So ether append the query string parameter yourself, remove the constraint, or switch to MVC recommend format of URL, e.g. /api/results/xxx.