【问题标题】:Asp.Net Core [FromQuery] bindingsAsp.Net Core [FromQuery] 绑定
【发布时间】: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。

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

【问题讨论】:

  • 尝试在 PaginationSettings 类中添加一个空的公共构造函数
  • @MarcusHoglund 现在可以使用了。你能告诉我为什么我应该使用一个空的公共构造函数吗?我已经有了带有 2 个参数的构造函数。
  • 添加了解释的答案

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


【解决方案1】:

来自docs

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

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

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

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 2018-12-17
    • 2018-09-19
    • 2018-11-02
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多