0

I have a problem with model binding using [FromQuery] attributes.

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:

[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.

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

3
  • 1
    Try to add an empty public constructor to the PaginationSettings class Commented Oct 11, 2018 at 6:10
  • @MarcusHoglund It works now. Could you please tell me why should I use an empty public constructor? I had already constructor with 2 parameters. Commented Oct 11, 2018 at 6:14
  • Added an answer to explain Commented Oct 11, 2018 at 6:22

1 Answer 1

5

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

public class PaginationSettings
{
    public PaginationSettings(){ }
    ...the other stuff
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.