Home > Blockchain >  Unable to get query string parameters to work in rest api with asp.net core 5.0
Unable to get query string parameters to work in rest api with asp.net core 5.0

Time:06-08

I need some help figuring out how I can get entities by name in this setup:

// get: /api/v1/users/
[HttpGet]
public virtual async Task<IActionResult> Get()
{
    var items = await service.GetAll();
    if (!items.Any()) return NotFound();
    return Ok(items);            
}

// get: /api/v1/users/{id}
[HttpGet("{id}")]
public virtual async Task<IActionResult> Get(int id)
{
    var item = await service.Get(id);
    if (item == null) return NotFound();
    return Ok(item);
}

// get: /api/v1/users/?name={name}
[HttpGet("{name}")]
public virtual async Task<IActionResult> Get([FromQuery]string name)
{
    var item = await service.GetByUserId(name);
    if (item == null) return NotFound();
    return Ok(item);
}

Get() and Get(int id) workes but when I call https://xxx/api/v1/users/?name=foo the Get() method is hit and all entities are returned. How can I get entities by name?

CodePudding user response:

The routing middleware maps an incoming request's URL into an appropriate action method. During this process, the middleware only uses URL segment values to identify a suitable action method. As a result, even if you specify the ?name="" value in a query string, the middleware always maps your request to the default Get() method.

You can solve this problem easily by modifying the URL paths (I believe, you know how to implement it). However, if you plan to keep your URL path as it is, then tweak your code a bit, and it will work.

    // get: /api/v1/users/
    // get: /api/v1/users/?name={name}
    [HttpGet]
    public virtual async Task<IActionResult> Get([FromQuery]string name)
    {
       if(name is null) return GetAllUsers();
       return return GetByUserName(name);
    }
  • Related