是否可以为整个控制器设置自定义ModelBinder? [英] Is it possible to set custom ModelBinder for the whole controller?
问题描述
我有一个自定义模型活页夹,我知道将其分配给我的操作方法的两种方法:
I've a custom model binder and I know two ways of assigning this to my action method:
方法之一:
public ActionResult MyAction([ModelBinder(typeof(MyCustomModelBinder))] ModelClass filter
或在global.asax.cs中全局:
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?
推荐答案
在模型绑定程序中,您可以访问ControllerContext.因此,根据那里可用的控制器信息来绑定模型应该很容易.
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.
它确实散发出一点气味,因为您正在模型绑定和控制器之间创建耦合.但是,如果您使用DI来创建策略模式,然后将绑定器解析器注入ModelBinderContainer中,然后使用其对系统的了解来选择所需的绑定,那么您将拥有解决方案.
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.
这篇关于是否可以为整个控制器设置自定义ModelBinder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!