3

I'm new in ASP Net Core 2, I want to bind different parameters that come from URL query string to action parameters in my action:

[HttpGet("{page}&{pageSize}&{predicate}", Name = "GetBuildingsBySearchCriteria")]
public IActionResult GetBuildingsBySearchCriteria([FromHeader] string idUser, [FromQuery]int page, [FromQuery]int pageSize, [FromQuery]string predicate)
{
    ....
}

When I test my action using postman, I set the idUser in header and other parameters in URL, example:

http://localhost:51232/api/buildings/page=1&pageSize=10&predicate=fr

The result is that I receive the idUser that I send from the header but other parameters are empty.

Do I miss something or what is wrong in my code?

1 Answer 1

5

If those parameter are meant to be in the query then there is no need for them in the route template

In

[HttpGet("{page}&{pageSize}&{predicate}", Name = "GetBuildingsBySearchCriteria")]

"{page}&{pageSize}&{predicate}" are placeholders in the route template, which is why the [FromQuery] fails to bind the parameters.

[FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding source you want to apply.

emphasis mine

Based on the example URL shown and assuming a root route, then one option is to use

[Route("api/[controller]")]
public class BuildingsController: Controller {

    //GET api/buildings?page=1&pageSize=10&predicate=fr
    [HttpGet("", Name = "GetBuildingsBySearchCriteria")]
    public IActionResult GetBuildingsBySearchCriteria(
        [FromHeader]string idUser, 
        [FromQuery]int page, 
        [FromQuery]int pageSize, 
        [FromQuery]string predicate) {
        //....
    }
}

or alternatively you can use them in the route like

[Route("api/[controller]")]
public class BuildingsController: Controller {

    //GET api/buildings/1/10/fr
    [HttpGet("{page:int}/{pageSize:int}/{predicate}", Name = "GetBuildingsBySearchCriteria")]
    public IActionResult GetBuildingsBySearchCriteria(
        [FromHeader]string idUser, 
        [FromRoute]int page, 
        [FromRoute]int pageSize, 
        [FromRoute]string predicate) {
        //....
    }
}

Reference Model Binding in ASP.NET Core

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

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.