无法使用[FromQuery] ASP Net Core 2 API绑定参数 [英] Can't bind params using [FromQuery] ASP Net Core 2 API

查看:90
本文介绍了无法使用[FromQuery] ASP Net Core 2 API绑定参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ASP Net Core 2的新手,我想将来自URL查询字符串的不同参数绑定到我的操作中的操作参数:

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)
{
    ....
}

当我使用邮递员测试动作时,我在标头中设置了 idUser ,在URL中设置了其他参数,例如:

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

结果是我收到了从标头发送的 idUser ,但其他参数为空.

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?

推荐答案

如果这些参数是要在查询中使用的,则路由中不需要它们>模板

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

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

"{page}& {pageSize}& {predicate}" route 模板中的占位符,这就是 [FromQuery] 绑定参数失败.

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

[FromHeader] [FromQuery] [FromRoute] [FromForm] :使用这些指定要应用的确切绑定源.

强调我的

根据显示的示例URL并假设使用根路由,那么一种选择是使用

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) {
        //....
    }
}

参考模型绑定在ASP.NET Core中

这篇关于无法使用[FromQuery] ASP Net Core 2 API绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆