【发布时间】:2019-03-16 03:03:06
【问题描述】:
我在使用 [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。
【问题讨论】:
-
尝试在 PaginationSettings 类中添加一个空的公共构造函数
-
@MarcusHoglund 现在可以使用了。你能告诉我为什么我应该使用一个空的公共构造函数吗?我已经有了带有 2 个参数的构造函数。
-
添加了解释的答案
标签: c# .net asp.net-core model-binding asp.net-core-webapi