簡體   English   中英

Asp.Net Core [FromQuery]綁定

[英]Asp.Net Core [FromQuery] bindings

使用[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; }
}

最后是Controller方法:

[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類添加一個公共默認構造函數( 默認構造函數是可以不帶任何參數調用的構造函數

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM