ASP.Net MVC HttpRequestValidationException - 捕获错误和捕获输入?

时间:2011-06-10 14:25:43

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

我已经看过几篇关于为控制器/动作关闭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.
}

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

1 个答案:

答案 0 :(得分:2)

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

public class MyModel
{
    public string ValidatedField {get; set;} // no HTML allowed here!

    [AllowHtml]
    public string NonValidatedField {get; set;} // user can enter HTML
}