Is it possible to have a non-public parameterless constructor that can be used for model binding?

前端 未结 2 1056
醉话见心
醉话见心 2021-01-24 20:39

I have a following POCO class. I don not want the parameterless constructor to be public.

public class FileDownloadRequest
    {
       //public FileDownloadRequ         


        
2条回答
  •  余生分开走
    2021-01-24 21:18

    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.

    Steps to take:

    • 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 the bindingContext;
    • Register the model binder, either through the ModelBinder attribute, or globally.

    Read more on custom bindings here.

提交回复
热议问题