【问题标题】:How to intercept my model before FluentValidation validate in ASP.NET MVC?如何在 ASP.NET MVC 中的 FluentValidation 验证之前拦截我的模型?
【发布时间】:2015-04-23 19:20:10
【问题描述】:

假设:

  1. FluentValidation 通过使用依赖注入与我的 ASP.NET MVC 5 Web 服务器集成。
  2. 已设置 FluentValidation 规则来验证我的模型属性,比如说propA

假设我有一个发布到 ASP.NET MVC 5 Web 服务器的页面,我的模型 propA 是根据用户输入的 TextBox 值设置的。但我想知道,是否可以在 FluentValidation 在验证我的模型的 Web 服务器中运行之前注入自己的序列化方法来更改 propA 的值?

有可能吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-5 fluentvalidation


    【解决方案1】:

    FluentValidation 和 DataAnnotation 方法的验证在模型绑定后工作,因此您可以为您的模型创建自定义 ModelBinder:

    public class YourBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = (YourModel)base.BindModel(controllerContext, bindingContext);
    
            model.PropA = model.PropA + " catched before validation";
            return model;
        }
    }
    

    在 global.asax 中注册

    protected void Application_Start()
    {
        ModelBinders.Binders.Add(typeof(YourModel), new YourBinder()); // asssociate model type with binder
    }
    

    并传递模型类型的参数:

    public ActionResult Submit(YourModel model) //YourBinder automatically used
    {
        if (ModelState.IsValid)
        {
            //...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2011-02-25
      • 2019-07-08
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      相关资源
      最近更新 更多