Cie*_*eja 0 .net c# model-binding asp.net-core 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);
}
}
Run Code Online (Sandbox Code Playgroud)
询问:
public class GetBlogListQuery : IRequest<IExecutionResult>
{
public string Filter { get; set; }
public PaginationSettings PaginationSettings { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
最后是控制器方法:
[HttpGet]
[ProducesResponseType(200)]
[ProducesResponseType(204)]
public async Task<IActionResult> GetBlogs([FromQuery] GetBlogListQuery query)
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用以下 URL 调用 Get,则会收到 HTTP 500。
来自文档
为了发生绑定,类必须有一个公共默认构造函数,并且要绑定的成员必须是公共可写属性。当模型绑定发生时,类只会使用公共默认构造函数实例化,然后可以设置属性
所以,为了使模型绑定工作。将公共默认构造函数(默认构造函数是可以不带参数调用的构造函数)添加到 PaginationSettings 类
public class PaginationSettings
{
public PaginationSettings(){ }
...the other stuff
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4935 次 |
| 最近记录: |