PROWAREtech

articles » archived » asp-net » redirect-404-errors

ASP.NET: Redirect 404 Errors

How to redirect 404 not found errors with ASPX Web Forms (.NET Framework).

ASP.NET makes it easy to retrieve the url that caused the 404 (not found) error and then it is easy to redirect to an appropriate replacement.

First, modify the web.config file.

Add a customErrors tag. This is for when a file is not found.

<system.web>
	<customErrors mode="RemoteOnly" defaultRedirect="/error404.aspx" redirectMode="ResponseRewrite">
		<error statusCode="404" redirect="/error404.aspx"/>
	</customErrors>
</system.web>

Add a httpErrors tag. This is for when a path/directory is not found.

<system.webServer>
	<httpErrors errorMode="Custom">
		<remove statusCode="404" subStatusCode="-1" />
		<error statusCode="404" prefixLanguageFilePath="" path="/error404.aspx" responseMode="ExecuteURL" />
	</httpErrors>
</system.webServer>

Now, create an error404.aspx WebForm and modify it as follows.

// error404.aspx.cs
public partial class error404 : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		string s = (Request.QueryString["aspxerrorpath"] ?? Request.RawUrl);
		if (s.StartsWith("/SomePath")) // if some paths were moved then this is a way to send them to a new location
		{
			Server.ClearError();
			Response.Redirect("http://www.newdomain.com" + s, true);
		}
		else
		{
			Response.StatusCode = 404;
			divErrorPath.InnerHtml = "<b>" + s + "</b> not found";
		}
	}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="error404.aspx.cs" Inherits="namespace.error404" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title>404 ERROR (NOT FOUND)</title>
</head>
<body>
	<div id="divErrorPath" runat="server" />
</body>
</html>


This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE