ASP.NET 核心 6 [FromQuery] return 绑定到对象时的空值

ASP.NET Core 6 [FromQuery] return null values when binding to object

一张图片胜过一千个字 - 如您在以下屏幕截图中所见,我无法检索查询字符串中的参数并将它们绑定到 ApplyFilter 模型。我试过 [BindQuery][BindProperty][Bind],但不幸的是一点运气都没有。即使参数传递给 QueryString.

,我仍然在过滤器参数上获取空值
https://localhost:7061/getallproducts?withproductoptions=true&categoryid=1&pricefrom=1&priceto=30&vendorname=ArtWithLight

代码:

public class ProductsController : ControllerBase
{
    private readonly IProductRepositery _prodRepo;

    public ProductsController(IProductRepositery prodRepo)
    {
        _prodRepo = prodRepo;
    }

    [HttpGet]
    public async Task<ActionResult<ProductDto>> GetAllProducts([FromQuery]ApplyFilter? filters)
    {
        return Ok(await _prodRepo.GetAllProductsAsync(filters));
    }
}

public class ApplyFilter
{
    public ApplyFilter()
    {
    }

    [FromQuery(Name = "categoryid")]
    List<int>? categoryIds { get; set; }
    [FromQuery(Name = "withproductoptions")]
    bool? withProductOptions { get; set; }
    [FromQuery(Name = "pricefrom")]
    decimal? priceFrom { get; set; }
    [FromQuery(Name = "priceto")]
    decimal? priceTo { get; set; }
    [FromQuery(Name = "vendorname")]
    string? vendorName { get; set; }
}

见截图:https://i.stack.imgur.com/qemMK.png

提前致谢。

试一试,已更新 ApplyFilter() 以使用 public 属性。 查看文档的 ASP.NET Core 6.0 Model Binding 部分,其中解释了它是如何工作的。

[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get([FromQuery] ApplyFilter filters)
    {
        return Ok();
    }

    public class ApplyFilter
    {
        public List<int>? CategoryIds { get; set; }
        public bool? WithProductOptions { get; set; }
        public decimal? PriceFrom { get; set; }
        public decimal? PriceTo { get; set; }
        public string? VendorName { get; set; }
    }
}

请求示例:

/Products?CategoryIds=1&CategoryIds=2&WithProductOptions=true&PriceFrom=10&PriceTo=20&VendorName=The%20Vendor