在《使用篇》中我们谈到扩展的验证编程方式,并且演示了本解决方案的三大特性:消息提供机制的分离多语言的支持多验证规则的支持,我们现在来看看这样的验证解决方案最终是如何实现的。

目录:
一、为验证创建一个上下文:ValidatorContext
二、通过自定义ActionInvoker在进行操作执行之前初始化上下文
三、为Validator创建基类:ValidatorBaseAttribute
四、通过自定义ModelValidatorProvider在验证之前将不匹配Validator移除
五、RequiredValidatorAttribute的定义

“基于某个规则的验证”是本解决方案一个最大的卖点。为了保持以验证规则名称为核心的上下文信息,我定义了如下一个ValidatorContext(我们本打算将其命名为ValidationContext,无奈这个类型已经存在)。ValidatorContext的属性RuleName和Culture表示当前的验证规则和语言文化(默认值为当前线程的CurrentUICulture),而字典类型的属性Properties用户存放一些额外信息。当前ValidationContext的获取与设置通过静态Current完成。

class ValidatorContext
   2: {
   3:     [ThreadStatic]
static ValidatorContext current;
   5:  
private set; }
private set; }
private set; }
   9:  
null)
  11:     {
this.RuleName = ruleName;
object>();
this.Culture = culture??CultureInfo.CurrentUICulture;
  15:     }
  16:  
static ValidatorContext Current
  18:     {
return current; }
value; }
  21:     }
  22: }

相关文章:

  • 2022-02-14
  • 2022-02-18
  • 2021-12-12
  • 2021-06-08
  • 2021-06-21
  • 2022-02-12
  • 2021-06-13
猜你喜欢
  • 2021-10-19
  • 2022-12-23
  • 2021-07-28
  • 2021-11-13
  • 2021-06-21
  • 2022-12-23
  • 2021-09-21
相关资源
相似解决方案