c# - 是否可以有一个可用于模型绑定(bind)的非公共(public)无参数构造函数?

标签 c# asp.net model-view-controller model-binding

我有一个后续的 POCO 类。我不希望公开无参数构造函数。

public class FileDownloadRequest
    {
       //public FileDownloadRequest() { }
        public FileDownloadRequest(int fileId, RepositoryFolderTypes fileType) //RepositoryFolderTypes is an enum, not a class
        {
            this.FileId = fileId;
            this.FileType = fileType;
        }
        public int FileId { get; set; }
        public RepositoryFolderTypes FileType { get; set; } //an enum
    }

当我尝试对以下 Controller 操作发出 https://10.27.8.6/Files/DownloadFile?fileId=1&folderType=SRC 请求时,我收到一条错误消息,指出不存在无参数构造函数这个对象。

[HttpGet]
public async Task<HttpResponseMessage> DownloadFile([FromUri] FileDownloadRequest request)
{
}

是否可以使用非公共(public)构造函数,还是绝对需要公共(public)构造函数?

最佳答案

是的,您可以使用任何您喜欢的构造函数,但是您必须自己进行模型绑定(bind)。问题出在 DefaultModelBinder.CreateModel 中,它使用了 parameterless public constructor .

您必须覆盖默认模型绑定(bind)器并创建您自己的模型绑定(bind)器。如果值得,时间由您决定。

采取的步骤:

  • 覆盖 CreateModel;
  • 检查 modelType 是否有一些通用约束,您需要在哪些模型上调用带参数的构造函数;
  • 调用Activator.CreateInstance(Type, Object[])与参数。您可以从 bindingContext;
  • 中获取它们的值
  • 通过 ModelBinder 属性或全局注册模型绑定(bind)器。

Read more on custom bindings here.

关于c# - 是否可以有一个可用于模型绑定(bind)的非公共(public)无参数构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44261895/

相关文章:

C#:使用滚动条缩放图片框图像的简单而实用的方法

时间:2019-03-17 标签:c#asyncwebclient

c# - 在 ASPX 页面上获取 'too many parameters passed' 到存储过程

asp.net - Release模式与调试 = "false"

java - struts 1 Action 映射可以调用 struts 2 Action 吗

c# - 在 ASP.net 中通过 Razor 输出电子邮件的语法

C# VLC 1.1 包装器

javascript - 文本区域滚动事件未被捕获

java - 将 JSF 理解为 MVC 框架

c# - 在 MVC 应用程序中显示/编辑 xml