Is it possible to set custom ModelBinder for the w

2019-07-15 10:48发布

问题:

I've a custom model binder and I know two ways of assigning this to my action method:

Either at the method:

public ActionResult MyAction([ModelBinder(typeof(MyCustomModelBinder))] ModelClass filter

Or globally in global.asax.cs:

ModelBinders.Binders.Add(typeof(MyCustomModelBinder))

But I wonder if there is a way to assign the custom model binder on the controller? So it works for all methods in the controller but not globally?

回答1:

In your model binder you have access to the ControllerContext. So it should be easy to bind your model based on the controller information you have available there.

It does smell a bit because you are creating a coupling between your model binding and the controller. But if you use DI to create a strategy pattern and inject a binder resolver into a ModelBinderContainer which then uses its knowledge of your system to choose the desired binding you would have your solution.



回答2:

No and as far as I know and it does not make much sense logically since a ModelBinder is bound to a Model either globally in the Binders collection (or by adding the attribute directly on the model class) or locally on a model in an action.

However you can still achieve what you want by creating an Aspect (as in from Aspect Oriented Programming) with a tool like PostSharp. You will be able to apply that aspect on the Controller level and it will inject the ModelBinder attributes on all methods as a post-compilation step. Question is whether you want to go through all this trouble and more importantly will it bring any value.

An example of an attribute decorator aspect is available in the PostSharp documentation here.