Can't bind params using [FromQuery] ASP Net Core 2 API

青春壹個敷衍的年華 提交于 2021-01-27 18:36:14

问题


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:


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



来源:https://stackoverflow.com/questions/50485052/cant-bind-params-using-fromquery-asp-net-core-2-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!