Asp.Net 核心 [FromQuery] 绑定

Asp.Net Core [FromQuery] bindings

我在使用 [FromQuery] 属性进行模型绑定时遇到问题。

我有以下 类:

public class PaginationSettings
{
    public const int DefaultRecordsPerPage = 5;

    public PaginationSettings(int pageIndex, int recordsPerPage)
    {
        RecordsPerPage = recordsPerPage == 0 ? DefaultRecordsPerPage : recordsPerPage;
        PageIndex = pageIndex == 0 ? 1 : pageIndex;
    }

    public int RecordsPerPage { get; set; }
    public int PageIndex { get; set; }
    public int RecordsStartIndex => RecordsPerPage * (PageIndex - 1);

    public static PaginationSettings Normalize(PaginationSettings source)
    {
        if (source == null)
        {
            return new PaginationSettings(0, 0);
        }

        return new PaginationSettings(source.PageIndex, source.RecordsPerPage);
    }
}

查询:

public class GetBlogListQuery : IRequest<IExecutionResult>
{
    public string Filter { get; set; }
    public PaginationSettings PaginationSettings { get; set; }
}

最后是控制器方法:

[HttpGet]
[ProducesResponseType(200)]
[ProducesResponseType(204)]
public async Task<IActionResult> GetBlogs([FromQuery] GetBlogListQuery query)
{
   ...
}

如果我尝试使用以下 URL 调用 Get,我会得到 HTTP 500。

http://localhost:5000/api/Blogs/GetBlogs?PaginationSettings.RecordsPerPage=2&PaginationSettings.PageIndex=2

来自docs

In order for binding to happen the class must have a public default constructor and member to be bound must be public writable properties. When model binding happens the class will only be instantiated using the public default constructor, then the properties can be set

所以,为了让模型绑定生效。向 PaginationSettings class

添加一个 public 默认构造函数( 默认构造函数是一个可以不带参数调用的构造函数
public class PaginationSettings
{
    public PaginationSettings(){ }
    ...the other stuff
}