验证上下文始终为 NULL?
我有这样的自定义验证属性:
public class MyCustomAttribute : ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if ((int)value == 100) {
// do some checking to validate & return ValidationResult accordingly
} else return ValidationResult.Success;
}
}
在这样的使用中:
[DisplayName("My Custom Property")]
[MyCustom(ErrorMessage = "ERROR!!!")]
public int? MyCustomProperty { get; set; }
我的问题是:为什么在 MyCustomAttribute 中的 IsValid 方法中,validationContext 始终为 NULL?我需要设置什么特殊的东西才能使其不为空吗?
I have custom validation attribute such as this:
public class MyCustomAttribute : ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if ((int)value == 100) {
// do some checking to validate & return ValidationResult accordingly
} else return ValidationResult.Success;
}
}
In usage like this:
[DisplayName("My Custom Property")]
[MyCustom(ErrorMessage = "ERROR!!!")]
public int? MyCustomProperty { get; set; }
My question is: why is it that inside MyCustomAttribute, within the IsValid method, validationContext is always NULL? Is there anything special I need to set to get it not to be NULL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你用来
检查数据是否有效,你必须使用
而不是
if you use
to check if data is valid you have to use
instead of
您必须覆盖 RequiresValidationContext
public override bool RequiresValidationContext =>; true;
它会起作用
you must override RequiresValidationContext
public override bool RequiresValidationContext => true;
it will work
我遇到了这个问题,事实证明这与我(不小心)在自定义 ValidationAttribute 中调用
base.IsValid(value, validationContext)
有关。例如,在
value == 100
为 true 且调用进入base.IsValid(value,validationContext)
的场景中,这会导致额外 调用我的自定义验证,在第二次调用中validationContext
为 null。我设法通过简单地删除对
base.IsValid(value,validationContext)
的调用来解决这个问题,这对我来说很好(我从来没有打算进行这个调用 - 它是自动生成代码的剩余部分)当使用智能感知覆盖该方法时)。但是我想在某些情况下您确实想要/需要调用基本实现。我不知道在这些情况下您会采取什么措施来解决错误。I had this issue and it turned out to be something to do with the fact I was (accidentally) calling
base.IsValid(value, validationContext)
within my custom ValidationAttribute. e.g.In the scenario were
value == 100
was true and the call went intobase.IsValid(value, validationContext)
, this was causing an additional call to my custom validation, and in the second callvalidationContext
was null.I managed to fix this by simply removing the call to
base.IsValid(value, validationContext)
, which was fine for me (I never intended to make this call - it was leftover from the auto-generate code when using intellisense to override the method). However I imagine there may be some cases where you do actually want/need to call the base implementation. I dont know what you would do to solve the error in these cases.