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