gpt4 book ai didi

c# - 是否可以为整个 Controller 设置自定义 ModelBinder?

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:26 25 4
gpt4 key购买 nike

我有一个自定义模型 Binder ,我知道将其分配给我的操作方法的两种方法:

要么在方法上:

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

或者全局在 global.asax.cs 中:

ModelBinders.Binders.Add(typeof(MyCustomModelBinder))

但我想知道是否有办法在 Controller 上分配自定义模型绑定(bind)器?所以它适用于 Controller 中的所有方法但不适用于全局?

最佳答案

在您的模型绑定(bind)器中,您可以访问 ControllerContext。因此,根据您在那里可用的 Controller 信息绑定(bind)您的模型应该很容易。

它确实有点味道,因为您在模型绑定(bind)和 Controller 之间创建了耦合。但是,如果您使用 DI 创建策略模式并将 Binder 解析器注入(inject) ModelBinderContainer,然后使用其对您的系统的了解来选择所需的绑定(bind),您就会得到您的解决方案。

关于c# - 是否可以为整个 Controller 设置自定义 ModelBinder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7036511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com