Send the right error codes in ASP.NET

by Mads Kristensen 10. April 2007 02:06

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

Tags: ,

ASP.NET | Security

Comments

8/24/2007 12:50:43 PM #

Jason Monroe

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

Jason Monroe United States |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008