When a request is 404 in ASP.NET on IIS 7 i want a custom error page to be displayed. The URL in the address bar should not change, so no redirect. How can i do this?
+2
A:
In your application's OnError event you can test for HttpExceptions with a status code of 404, and then do a Server.Transfer to your custom 404 page, instead of a Response.Redirect. Have a look at http://blog.dmbcllc.com/2009/03/02/aspnet-application_error-detecting-404s/
Ravish
2009-09-02 14:17:49
A:
I use an http module to handle this. It works for other types of errors, not just 404s, and allows you to continue using the custom errors web.config section to configure which page is displayed.
public class CustomErrorsTransferModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.Error += Application_Error;
}
public void Dispose() { }
private void Application_Error(object sender, EventArgs e)
{
var error = Server.GetLastError();
var httpException = error as HttpException;
if (httpException == null)
return;
var section = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
if (section == null)
return;
if (!AreCustomErrorsEnabledForCurrentRequest(section))
return;
var statusCode = httpException.GetHttpCode();
var customError = section.Errors[statusCode.ToString()];
Response.Clear();
Response.StatusCode = statusCode;
if (customError != null)
Server.Transfer(customError.Redirect);
else if (!string.IsNullOrEmpty(section.DefaultRedirect))
Server.Transfer(section.DefaultRedirect);
}
private bool AreCustomErrorsEnabledForCurrentRequest(CustomErrorsSection section)
{
return section.Mode == CustomErrorsMode.On ||
(section.Mode == CustomErrorsMode.RemoteOnly && !Context.Request.IsLocal);
}
private HttpResponse Response
{
get { return Context.Response; }
}
private HttpServerUtility Server
{
get { return Context.Server; }
}
private HttpContext Context
{
get { return HttpContext.Current; }
}
}
enable in your web.config in the same way as any other module
<httpModules>
...
<add name="CustomErrorsTransferModule" type="WebSite.CustomErrorsTransferModule, WebSite" />
...
</httpModules>
David Walker
2009-09-02 16:27:35