为 Razor Pages 使用非默认构造函数

Use non-default constructor for Razor Pages

我有一个使用 Razor Pages 和 Mediatr 的 asp.net 核心 2.2 Web 应用程序。

我的查询在 Jimmy Bogard 的博客中有私有设置器 described

public class Query : IRequest<Result>
{
    public Query(string needle)
    {
        this.Needle = needle;
    }

    public string Needle { get; private set; }
}

当我在我的网站上使用它时 api 没问题(即使 也不需要)

但是当我使用 Razor Pages 时出现错误,因为查询中没有无参数构造函数:

public class SearchModel : PageBaseModel
{
    public SearchModel(IMediator mediator)
        : base(mediator)
    {
    }

    [BindProperty(SupportsGet = true)]
    public Accounts.Search.Query Query { get; set; }

    public Accounts.Search.Result Result { get; private set; }

    public async Task<IActionResult> OnGetAsync(CancellationToken cancellationToken)
    {
        Result = await this.Mediator.Send(Query, cancellationToken);

        return this.Page();
    }
}

是否可以使用私有 setter 进行模型绑定(无需为每个查询编写 custom IModelBinder)?

Is it possible to use private setters for model binding (without writting custom IModelBinder for every query)?

强调我的

简答:否

在这里回答很长Model Binding in ASP.NET Core: Complex types

A complex type must have a public default constructor and public writable properties to bind. When model binding occurs, the class is instantiated using the public default constructor.

再次强调我的

我相信您通过尝试使用不可变消息请求作为绑定模型来混淆问题。