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;
    }    
}    

Disable Browser Back Button

Push the history forward in the page you want to stop the user from going back to the previous page. 

  $(function() {
      window.history.forward();
  });

 

.NET Get Relative URL - ResolveClientUrl - MVC and WebForms

I needed to get the relative path to an image based on the URL in a static class.

Typically I would just use Page.ResolveClientUrl but that does not work in a class that does not inherit the page object.  Here is a snippet of code to cast HttpContext to a Page object. 

Webforms: This the code using in ASP.NET Webforms to get the relative URL in a base class
           
//Get the Full Path based on the page.             
//This will return /folder/image.jpg or something like ../folder/image.jpg
HttpContext CTX = HttpContext.Current;
System.Web.UI.Page page = (System.Web.UI.Page)HttpContext.Current.Handler;
var ImageFullPath = page.ResolveClientUrl(folderName + @"/" + imageName);
MVC: This the code using in ASP.NET MVC to get the relative URL in a base class
           
//Create the Chart and save it
HttpContext CTX = HttpContext.Current;            
var ServerPath = CTX.Server.MapPath(ImgTempFolder);
var ImgName = c.makeTmpFile(ServerPath); //This is using ChartDirector. Replace your URL here.           

var VPath = VirtualPathUtility.ToAbsolute(ImgTempFolder) + ImgName;
return VPath;