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

本文关键字:输入 错误 Net HttpRequestValidationException- ASP MVC | 更新日期: 2023-09-27 17:58:47

我看到过几篇关于关闭控制器/操作的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.
}

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

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

您签出AllowHTML属性了吗?这可能正是你所需要的。

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