如何在生产中捕获HttpRequestValidationException

我有这段代码来处理我的global.asax.cs文件中的HttpRequestValidationException。

protected void Application_Error(object sender, EventArgs e) { var context = HttpContext.Current; var exception = context.Server.GetLastError(); if (exception is HttpRequestValidationException) { Response.Clear(); Response.StatusCode = 200; Response.Write(@"hello"); Response.End(); return; } } 

如果我调试我的webapplication,它的工作完美。 但是当我把它放在我们的生产服务器上时,服务器会忽略它并生成“ 从客户端检测到一个有潜在危险的request.form值 ” – 错误页面。 我不知道到底发生了什么……如果有人知道问题是什么,或者我做错了什么……?

另外,我不想在web.config中将validaterequest设置为false。

服务器使用IIS7.5,我使用的是asp.net 3.5。

谢谢,布鲁诺

好吧,我发现它是我的自我。 我必须清除我的上一个错误。

 protected void Application_Error(object sender, EventArgs e) { var context = HttpContext.Current; var exception = context.Server.GetLastError(); if (exception is HttpRequestValidationException) { context.Server.ClearError(); // Here is the new line. Response.Clear(); Response.StatusCode = 200; Response.Write(@"hello"); Response.End(); return; } } 

另一种仅适用于MVC的方法是使用自定义exceptionfilter:

  • 创建一个实现IExceptionFilter的自定义FilterAttribute
  • 从FilterAttribute内部,您可以重定向到控制器或视图以用于显示错误。
  • 在Global.asax中注册filter或将控制器属性

这样做的好处是您可以使用普通的MVC基础结构(Razor)来呈现错误视图。

 public class HttpRequestValidationExceptionAttribute : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { if (!filterContext.ExceptionHandled && filterContext.Exception is HttpRequestValidationException) { filterContext.Result = new RedirectResult("~/HttpError/HttpRequestValidationError"); filterContext.ExceptionHandled = true; } } }