How to catch HttpRequestValidationException in production
Ok, i found it my self.I must clear my last error.
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(@"<html><head></head><body>hello</body></html>"); Response.End(); return; }}
Another way that only works with MVC is using a custom Exception Filter:
- Create a custom FilterAttribute that implements IExceptionFilter
- from inside the FilterAttribute, you can redirect to the controller or view to be used to display the error.
- register the filter in the Global.asax or attribute your controllers
This has the advantage that you can use the normal MVC infrastructure (Razor) to render the error view.
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; } }}