rid00z
rid00z

Reputation: 1616

ASP.NET Custom Error except 404 errors,

I have setup custom error as follows..

protected void Application_Error(Object sender, EventArgs e)
{
    Exception ex = HttpContext.Current.Server.GetLastError();
    if (ex is HttpUnhandledException && ex.InnerException != null)
        ex = ex.InnerException;
    if (ex != null)
    {
        try
        {
            Logger.Log(LogEventType.UnhandledException, ex);
        }
        catch
        { }
    }

    HttpContext.Current.Server.ClearError();
    Response.Redirect(MyCustomError);

}

I am wondering if it is possible to detect if this error is a 404 error, and then show the default 404 error?

Upvotes: 4

Views: 1814

Answers (2)

dlamblin
dlamblin

Reputation: 45321

I have to say I'm really confused about why you're clearing whatever error happened and then redirecting to a custom error page in the first place.

Maybe change:

HttpContext.Current.Server.ClearError();
Response.Redirect(MyCustomError);
//to
if (!(ex is HttpException && 404 == ((HttpException)ex).getHttpCode())){
  HttpContext.Current.Server.ClearError();
  Response.Redirect(MyCustomError);
}

Otherwise don't do any of these checks and leave any file not found exceptions be. Have them be handled by your custom error handlers defined in the web.config via the framework.

<customErrors mode="RemoteOnly" defaultRedirect="~/Error/500.htm">
    <error statusCode="500" redirect="~/Error/500.htm"/>
    <error statusCode="404" redirect="~/Error/404.htm"/>
</customErrors>

And if you aren't seeing the handling you want change the mode to "On".

If you need to throw a 404, maybe because the requested item's ID has been deleted from the DB, then throw the appropriate HttpException error.

Upvotes: 6

Chris
Chris

Reputation: 40613

I'm pretty sure that requests for static files do not go through the Asp.Net framework - only files that end in .aspx do. So a request for a static file that doesn't exist will get a 404 from IIS, but not get processed by asp.net.

You could do a similar thing to as described on this page under the heading 'IIS Custom 401 Errors':

http://msdn.microsoft.com/en-us/library/ms972958.aspx

The gist of it is to create a custom error handler in iis that sends the user to a certain static htm file, which redirects them to your special 404 handler aspx page.

Upvotes: 1

Related Questions