问题描述
我有一个以下的POCO课程.我不希望无参数构造函数是公开的.
I have a following POCO class. I don not want the parameterless constructor to be public.
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
}
当我尝试对以下控制器操作执行https://10.27.8.6/Files/DownloadFile?fileId=1&folderType=SRC
请求时,收到一条错误消息,指出该对象不存在无参数构造函数.
When I am trying a https://10.27.8.6/Files/DownloadFile?fileId=1&folderType=SRC
request to the following controller action, I get an error saying that no parameterless constructor exists for this object.
[HttpGet]
public async Task<HttpResponseMessage> DownloadFile([FromUri] FileDownloadRequest request)
{
}
是否可以有一个非公共的构造函数,还是绝对需要一个公共的构造函数?
Is it possible to have a non-public constructor, or is a public one absolutely required?
推荐答案
是的,您可以使用任何喜欢的构造函数,但随后您必须自己绑定模型.问题出在DefaultModelBinder.CreateModel
中,它使用无参数公共构造函数.
Yes, you can use any constructor you like, but you will have to do the model binding yourself then. The problem is in DefaultModelBinder.CreateModel
, which uses a parameterless public constructor.
您必须覆盖默认的模型活页夹并创建自己的活页夹.如果那是值得的,那么时间取决于您.
You have to override the default model binder and create your own. If that is worth the time is up to you.
采取的步骤:
- 覆盖
CreateModel
; - 检查
modelType
是否存在一些通用约束,您需要使用哪些参数调用构造函数并使用参数; - 致电
Activator.CreateInstance(Type, Object[])
与参数.您可以从bindingContext
; 获取它们的值 - 通过
ModelBinder
属性或全局注册模型绑定器.
- Override
CreateModel
; - Check the
modelType
for some generic constraint which models you need to call the constructor with parameters on; - Call
Activator.CreateInstance(Type, Object[])
with the parameters. You could obtain their values from thebindingContext
; - Register the model binder, either through the
ModelBinder
attribute, or globally.
这篇关于是否可以使用可用于模型绑定的非公共无参数构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!