I have this piece of code to handle the HttpRequestValidationException in my global.asax.cs file.
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(@"<html><head></head><body>hello</body></html>");
Response.End();
return;
}
}
If I debug my webapplication, it works perfect. But when i put it on our production-server, the server ignores it and generate the “a potentially dangerous request.form value was detected from the client” – error page.
I don’t know what happens exactly…
If anybody knows what the problem is, or what i do wrong..?
Also I don’t want to set the validaterequest on false in the web.config.
The server uses IIS7.5, And I’m using asp.net 3.5.
Thanks,
Bruno
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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;
}
}
Method 2
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;
}
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0