如何将ASP.NET MVC3请求验证异常作为模型或属性验证错误处理

时间:2012-02-13 14:50:11

标签: asp.net-mvc-3 model-validation request-validation

我的问题很有希望。 提交表单后,我想将包含无效字符(特别是HTML)的所有属性(字段)标记为模型错误。 我面临的问题是请求验证在 模型绑定/验证之前启动,我得到HTTP 500 ... 我看到similar question在您的Model / ViewModel上使用[AllowHtml]属性属性或在web.config中使用<httpRuntime requestValidationMode="2.0" />做广告,但我要找的是如何“ < em>全局捕获请求验证异常并将其显示为模型错误 “。此外,我不想“剥离”HTML标签,我想通知用户他们的输入无效。

我考虑使用正则表达式验证属性来查找错误的输入,但正如我所提到的,ASP.NET MVC3上的请求验证发生在模型绑定/验证之前,所以这是一个禁忌......

非常good overview of the Request Validation can be found here

1 个答案:

答案 0 :(得分:10)

我认为您的唯一目的是在模型绑定期间获取请求验证异常,并将错误显示为模型状态错误。这是样本,

    using System.Web.Helpers;
    public class MyModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                return base.BindModel(controllerContext, bindingContext);
            }
            catch(HttpRequestValidationException ex)
            {
                var modelState = new ModelState();
                modelState.Errors.Add(ex.Message);
                var key=bindingContext.ModelName;
                var value = controllerContext.RequestContext.HttpContext.Request.Unvalidated().Form[key];
                modelState.Value = new ValueProviderResult(value, value,CultureInfo.InvariantCulture);
                bindingContext.ModelState.Add(key, modelState);
            }
            return null;
        }
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        ModelBinders.Binders.DefaultBinder = new MyModelBinder();
    }

这将在模型状态中添加请求验证的例外。对不起,如果我不明白你的问题。