简体   繁体   English

Asp.Net Core [FromQuery]绑定

[英]Asp.Net Core [FromQuery] bindings

I have a problem with model binding using [FromQuery] attributes. 使用[FromQuery]属性进行模型绑定时出现问题。

I have the followings classes: 我有以下课程:

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);
    }
}

Query: 查询:

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

and finally Controller method: 最后是Controller方法:

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

If I try to call Get with the following URL I get HTTP 500. 如果尝试使用以下URL调用Get,则会得到HTTP 500。

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

From the 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 发生模型绑定时,将仅使用公共默认构造函数实例化该类,然后可以设置属性

So, in order to make the model binding work. 因此,为了使模型绑定起作用。 Add an public default constructor ( A default constructor is a constructor which can be called with no arguments ) to the PaginationSettings class 向PaginationSettings类添加一个公共默认构造函数( 默认构造函数是可以不带任何参数调用的构造函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM