Sunday, July 29, 2012

Proper error handling in ASP.NET Web Forms


I want to show users two custom pages:
1) Error500.aspx -- for uncaught exceptions.
2) Error404.aspx -- for non-existing page.

The trick is that ASP.NET handles requests to *.aspx pages differently than to other types of pages.

Here's how I do it.

In Web.Config:

<system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx" redirectMode="ResponseRewrite">
               <error statusCode="404" redirect="~/Error404.aspx"/>
               <error statusCode="500" redirect="~/Error500.aspx"/>
        customErrors>
system.web>

<system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
               <add name=" PostJobFreeModule" type="PostJobFree.PostJobFreeModule" preCondition="managedHandler"/>
        modules>
        <httpErrors existingResponse="PassThrough" />
system.webServer>

In PostJobFreeModule.cs I use:
void application_EndRequest(object sender, EventArgs e)
{
        PageNotFoundHelper.ShowError404IfNeeded();
}

public static class PageNotFoundHelper
{
        public static void Set404StatusCode()
        {
                HttpContext.Current.Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
               HttpContext.Current.Items["Set404StatusCode"] = true;
        }
 
        public static void ShowError404IfNeeded()
        {
               if (!HttpContext.Current.IsCustomErrorEnabled) return;
               if (HttpContext.Current.Response.StatusCode == 404)
               {
                       if (HttpContext.Current.Items["Set404StatusCode"] == null)
                       {
                               HttpContext.Current.Server.Transfer("~/Error404.aspx");
                       }
               }
        }
}

No comments:

Followers

About Me

My photo
Email me: blog@postjobfree.com