Asp.Net Core [FromQuery]绑定

时间:2018-10-11 05:54:38

标签: c# .net asp.net-core model-binding asp.net-core-webapi

我在使用[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; }
}

最后是Controller方法:

[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

1 个答案:

答案 0 :(得分:2)

docs

  

为了使绑定发生,该类必须具有公共默认值   构造函数和要绑定的成员必须是公共可写属性。   当模型绑定发生时,该类将仅使用实例化   公共默认构造函数,则可以设置属性

因此,为了使模型绑定起作用。向PaginationSettings类添加一个公共默认构造函数(默认构造函数是可以不带参数调用的构造函数

public class PaginationSettings
{
    public PaginationSettings(){ }
    ...the other stuff
}