Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core Web API Controller action with many parameters

I have ASP.Net Core Web API Controller's method that returns List<Car> based on query parameters.

[HttpPost("cars")]
public async Task<List<Car>> GetCars([FromBody] CarParams par)
{
    //...
}

Parameters are grouped in record type CarParams. There are about 20 parameters:

public class CarParams
{
    public string EngineType { get; set; }
    public int WheelsCount { get; set; }
    /// ... 20 params
    public bool IsTruck { get; set; }
}

I need to change this method from POST to GET, because I want to use a server-side caching for such requests.

Should I create a controller's method with 20 params?

[HttpGet("cars")]
public async Task<List<Car>> GetCars(string engineType, 
                                      int wheelsCount, 
                                  /*...20 params?...*/
                                         bool isTruck)
{
    //...
}

If this is the case: Is there a way to automatically generate such a complex URL for a client-side app?

like image 230
AsValeO Avatar asked Mar 05 '23 23:03

AsValeO


1 Answers

You can keep the model. Update the action's model binder so that it knows where to look for the model data.

Use [FromQuery] to specify the exact binding source you want to apply.

[HttpGet("cars")]
[Produces(typeof(List<Car>))]
public async Task<IActionResult> GetCars([FromQuery] CarParams parameters) {

    //...

    return Ok(data);
}

Reference Model Binding in ASP.NET Core

like image 113
Nkosi Avatar answered Mar 31 '23 15:03

Nkosi