C# – 404 page that displays requested page

asp-classicasp.netc++umbracovb.net

I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem.

How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using:

request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server.

But that didn't work.

Any Ideas?

The site is on IIS 6.0.
We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.

Best Solution

I do basically the same thing you ask in a custom 404 error handling page. On IIS 6 the original URL is in the query string. The code below shows how to grab the original URL and then forward the user. In my case I switched from old ASP to new ASP.NET, so all the .asp pages had to be forwarded to .aspx pages. Also, some URLs changed so I look for keywords in the old URL and forward.

//did the error go to a .ASP page?  If so, append x (for .aspx) and 
//issue a 301 permanently moved
//when we get an error, the querystring will be "404;<complete original URL>"
string targetPage = Request.RawUrl.Substring(Request.FilePath.Length);

if((null == targetPage) || (targetPage.Length == 0))
    targetPage = "[home page]";
else
{
     //find the original URL
    if(targetPage[0] == '?')
    {
        if(-1 != targetPage.IndexOf("?aspxerrorpath="))
             targetPage = targetPage.Substring(15); // ?aspxerrorpath=
        else
             targetPage = targetPage.Substring(5); // ?404;
        }
        else
        {
             if(-1 != targetPage.IndexOf("errorpath="))
             targetPage = targetPage.Substring(14); // aspxerrorpath=
             else
            targetPage = targetPage.Substring(4); // 404;
        }
    }               

    string upperTarget = targetPage.ToUpper();
    if((-1 == upperTarget.IndexOf(".ASPX")) && (-1 != upperTarget.IndexOf(".ASP")))
    {
        //this is a request for an .ASP page - permanently redirect to .aspx
        targetPage = upperTarget.Replace(".ASP", ".ASPX");
        //issue 301 redirect
        Response.Status = "301 Moved Permanently"; 
        Response.AddHeader("Location",targetPage);
        Response.End();
    }

    if(-1 != upperTarget.IndexOf("ORDER"))
    {
                //going to old order page -- forward to new page
               Response.Redirect(WebRoot + "/order.aspx");
           Response.End();
    }
Related Question