4

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?

1
  • 1
    You are aware of the URL length limitation? Commented Jun 17, 2018 at 21:11

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

[Produces(typeof(List<Car>))] attribute required because return type of method is Task<IActionResult>? ASP.NET Core introduces IActionResult<T>, so this attribute will not be required anymore?
How request URL should look like for this controller, please provide example. Is there a way to generate URL with query params from given CarParams object?
I've found a QueryBuilder class.
Just for reference URL may look like following: localhost:12345/api/controllerName/… While Model Binding will map values to properties of parameter type.
1

Just change [FromBody] attribute with [FromUrl]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.