Send the right error codes in ASP.NET

Apr 9, 2007

If you have a broken internal link on your ASP.NET website and follow it, you will see the well known yellow screen of death (YSOD). Not only is it ugly, but it could also tell the visitor more than they should know about your system. The broken link sends a 404 HTTP status code to the client, but instead of providing the visitor with the YSOD, it will be better to use the browsers build-in view for those kinds of errors. It’s a view visitors know and not an arbitrary YSOD with strange information.

Of course, this is only true if you have no custom error HTML page. Keep in mind that custom error aspx pages are not good enough, because if a global ASP.NET exception occurs, then they won’t work either.

You can bypass the default YSOD by adding this method to the global.asax.

private void Application_Error(object sender, EventArgs e)
{
 HttpException ex = Server.GetLastError() as HttpException;
 if (ex !=null)
 {
  // When a HttpException occurs.
  Response.StatusCode = ex.GetHttpCode();
 }
 else
 {
  // When any other exception occurs.
  Response.StatusCode = 500;
 }

 Response.End();
}

The mothod removes the YSOD and let’s the browser decide what to display to the visitor.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (1) -

Jason Monroe
Jason Monroe United States
8/24/2007 3:50:43 AM #

I know that I'm coming in rather late on your blog.. but I'm reading every post while I wait for VS 2005 TS and VS2005 SP1 to install on a new VM...

As a developer, I like to see the YSOD.. so I would wrap your could around a check to see if debug is enabled or not..

<code>
    void Application_Error(object sender, EventArgs e)
    {
        if (!HttpContext.Current.IsDebuggingEnabled)
        {
            HttpException ex = Server.GetLastError() as HttpException;
            if (ex != null)
            {
                // When a HttpException occurs.
                Response.StatusCode = ex.GetHttpCode();
            }
            else
            {
                // When any other exception occurs.
                Response.StatusCode = 500;
            }

            Response.End();
        }
    }
</code>

Oh yea. the comment needs a code syntax highlighter... [code] and [/code].  You can start with c# since that's the only language that matters anyway Smile

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.