修改模型后,如何在继承自 DefaultModelBinder 的自定义模型绑定器中重新验证模型?
我有一个继承自 DefaultModelBinder 的自定义模型绑定器。我想要它做的是在模型上设置一个无法由 DefaultModelBinder 解析的属性。它看起来像这样:
public class FooModelBinder : DefaultModelBinder {
public override void BindModel(ControllerContext controllerContext, ModelBindingContext modelBindingContext)
{
var model = base.BindModel(controllerContext, bindingContext);
((IFooModel)model).Bar = GetBarFromSomewhere();
return model;
}
}
但是,由于 IFooModel 中的 Bar 属性不能为 null,并且我使用 FluentValidation 并有一条规则,在我调用 base.BindModel 后,ModelState 将无效。
因此,我想在调用 base.BindModel 时避免验证模型,或者至少清除错误并在设置 Bar 属性后重新验证模型。
我已经尝试解析验证器并验证模型,但我似乎无法让它实际运行验证,并且它不会导致任何错误(即使它应该):
var validators = bindingContext.ModelMetadata.GetValidators(controllerContext);
foreach(var validator in validators) {
foreach (var result in validator.Validate(model)) {
bindingContext.ModelState.AddModelError(result.MemberName, result.Message);
}
}
在返回模型之前运行此命令之后,验证器包含 FluentValidationModelValidator,但是当我调用 validator.Validate 时,我没有收到任何错误。我的模型上有另一个属性,当我之前运行 base.BindModel 时,它确实导致了错误,所以我预计这里会发生相同的错误。
I have a custom model binder inheriting from DefaultModelBinder. What I want it to do is to set a property on the model, that can't be resolved by the DefaultModelBinder. It looks like this:
public class FooModelBinder : DefaultModelBinder {
public override void BindModel(ControllerContext controllerContext, ModelBindingContext modelBindingContext)
{
var model = base.BindModel(controllerContext, bindingContext);
((IFooModel)model).Bar = GetBarFromSomewhere();
return model;
}
}
However, since the Bar property in IFooModel cannot be null and I'm using FluentValidation with a rule saying that, the ModelState will be invalid after I've called base.BindModel.
So I would like to either avoid validating the model when calling base.BindModel, or at least clear the errors and re-validate the model after I've set the Bar property.
I've tried resolving the validators and validating the model, but I can't seem to get it to actually run the validation, and it doesn't result in any errors (even when it should):
var validators = bindingContext.ModelMetadata.GetValidators(controllerContext);
foreach(var validator in validators) {
foreach (var result in validator.Validate(model)) {
bindingContext.ModelState.AddModelError(result.MemberName, result.Message);
}
}
After running this before I return model, validators contains a FluentValidationModelValidator, but when I call validator.Validate I don't get any errors. I have another property on my model which did cause an error when I ran base.BindModel earlier, so I would expect the same error to occur here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试重写
BindProperty
方法,而不是重写BindModel
方法:Instead of overriding the
BindModel
method you could try overriding theBindProperty
method: