Send the Right error codes in Asp.net

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();
    }

No comments:

Post a Comment