您好我是asp net mvc编程的新手,我想知道为什么我的CustomModelBinder类的OnPropertyValidating方法没有被调用。
这是我对CUstomModelBinder的声明。
public class TestModelBinder : DefaultModelBinder
{
protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
if (value is string && (controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)))
{
if (controllerContext.Controller.ValidateRequest && bindingContext.PropertyMetadata[propertyDescriptor.Name].RequestValidationEnabled)
{
int index;
if (IsDangerousString(value.ToString(), out index))
{
throw new HttpRequestValidationException("Dangerous Input Detected");
}
}
}
return base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
}
}
以下是我添加到Global.asax
的内容 ModelBinders.Binders.Add(typeof(TestModelBinder), new TestModelBinder());
ModelBinders.Binders.DefaultBinder = new TestModelBinder();
现在我假设每次调用控制器动作时都会调用此OnPropertyValidating方法:
[HttpPost]
public JsonResult TestMethod(int param1, string param2, string param3)
{
...
}
但我的customModelBinder上的OnPropertyValidating方法永远不会被调用。
任何人都可以帮我理解原因吗?有什么好的教程网站吗?
提前感谢!
答案 0 :(得分:2)
而不是:
ModelBinders.Binders.Add(typeof(TestModelBinder), new TestModelBinder());
这样做:
ModelBinders.Binders.Add(typeof(<your model>), new TestModelBinder());