If you like to keep the page directive validateRequest="true" and handle the exception myself so that I wouldn't show the standard error page, the following way will not work because the request validation occurs before your page starts executing. Hence, using a Try/Catch block within the page is simply too late, the exception has already been thrown.
void btn_Click(object sender, System.EventArgs e)
{
try
{
....
} catch(System.Web.HttpRequestValidationException ex)
{
......;
}
}
There are three ways to handle the issue.
Configurating customErrors in Web.config
First, you need to set up an error page. Within the <system.web> section of your web.config file, add the following:
<customErrors mode ="On" >
<error statusCode="500" redirect="error500.aspx" />
</customErrors>
We do this because if the request validation fails, it changes the status of the response from 200 (OK) to 500 (Internal Error). The above setting in our web.config will tell our ASP.NET application not to show the ugly exception message, but instead show the error500.aspx page.
Or you can use the customErrors section of the web.config to push all errors to a default error page:
<configuration>
<system.web>
<customErrors defaultRedirect="Error.aspx" mode="RemoteOnly">
</customErrors>
</system.web>
</configuration>
Creating a page-level error handler
You may wish to create a page-level error handler (the above is at the application-level). Add the following to your page or its codebehind:
protected override void OnError(EventArgs e)
{
if(Server.GetLastError().GetBaseException() is System.Web.HttpRequestValidationException )
{
Response.Clear();
Response.Write( "Invalid characters." );
Response.StatusCode = 200;
Response.End();
}
}
Here you have used the page-level OnError method to handle the request validation failure.
The awkward part here is that you must finish the request inside this block. you must create our HTML response, change the status code of the response, and then end the response. If you do not finish the request within this block, the exception will re-occur, and you are back to the 500 Internal Error status. (Comment out the Response.End() line to see this occur.)
Handling Application_Error in global.asax
In the global.asax file for your application, you can add an Application_Error event handler. Call Context.ClearError() before redirecting, like below:
protected void Application_Error(object src, EventArgs e)
{
Exception ex = Server.GetLastError();
if ex is HttpRequestValidationException)
{
// do whatever you want to the error itself (ex.Message, etc.)
}
// clear out the ASP.Net error
Context.ClearError();
// redirect to an error page
Response.Redirect("errorpage.aspx");
}