How to Break out of ASP.NET Application_Error and redirect to a different page

A site I developed was getting the error: "A potentially dangerous Request.Path value was detected from the client (&)."

This was due to how Google was indexing the pages on the site. The site is using Friendly URLs (meaning no ?Param= or &Parm=).  Then Google appended the following parameters (and other values) to the end of the URL: &ct=ga&cd=.

Since there was no ?Param= .NET saw the &ct=ga&cd= as a hack.  This lead me down the path of trapping that error in the Global.asax Application_Error handled. When the  "A potentially dangerous Request.Path value was detected from the client (&)." error was thrown I wanted to redirect to the default home page.  

The problem was the redirect did not work and the site kept going back to the custom error message page. I then found by setting Server.ClearError() I could redirect to the home page. 
void Application_Error(object sender, EventArgs e)
{
    //... other code here....

    var Message = ex.Message.ToLower();
    var RootURL = Common.GetAppPathMasterPages() + "default.aspx";
                
    if (Message.Contains("does not exist") || Message.Contains("potentially dangerous request"))
    {
        Server.ClearError();
        CTX.Response.Redirect(RootURL);
        return;
    }    
}    
Comments are closed