【问题标题】:ASP.Net MVC HttpRequestValidationException - Catch Error and Capture Input?ASP.Net MVC HttpRequestValidationException - 捕获错误并捕获输入?
【发布时间】:2011-09-12 13:23:30
【问题描述】:

我已经看过几篇关于关闭控制器/操作的 HttpRequestValidation 以解决此错误的帖子,但我真的希望它在大多数情况下都启用。我想绕过验证的情况很少,我愿意在其周围包裹一个 try/catch 块:

string searchTerm = string.Empty;
try {
    searchTerm = Request.QueryString["q"];
} catch (HttpRequestValidationException ex) {
    // What can I do here to capture the value? Is parsing the error message the only way?
    // Seems like ex.Data property would be a good place for Microsoft to stick values if
    // people wanted to do something with them, but ex.Data is empty.
}

同样,这仅适用于表单中的某些字段,因此我不想禁用对整个控制器或操作的验证。我希望为我没有专门处理的字段提供额外的保护。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3 error-handling


    【解决方案1】:

    您检查了AllowHTML 属性吗?它可能正是您所需要的。

    public class MyModel
    {
        public string ValidatedField {get; set;} // no HTML allowed here!
    
        [AllowHtml]
        public string NonValidatedField {get; set;} // user can enter HTML
    }
    

    【讨论】:

    • 完美,谢谢。只需要创建一个视图模型,而不是直接从查询字符串中提取它。
    猜你喜欢
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 2010-10-02
    • 2012-08-01
    • 1970-01-01
    • 2019-01-20
    相关资源
    最近更新 更多