views:

25

answers:

2

OK I have the following code in my Global.asax file:

void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
        Exception objError = Server.GetLastError().GetBaseException();

        Response.Redirect(
            String.Format(
            "/Error/{0}/{1}",
            ((HttpException)objError).GetHttpCode(),
            Request.RawUrl));
}

To provide neat and tidy error urls like "/Error/404/TheNameOfTheRequestedPage". This works fine from VS 2008, but once published to my local machine, I get the default error page:

Error Summary

HTTP Error 404.0 - Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable

Anyone know how to do this? I've chosen not to use system.web/customErrors because I don't have access to Server.GetLastError() from there (or at least it's never worked for me) and I want to get the http code.

A: 

This is most likely related to you triggering an IIS Http Error which is defined in the web.config under the nodes

<system.webServer>    
    <httpErrors>
    </httpErrors>    
<system.webServer>

If the issue is you're returning an a response code for 404 and getting the IIS 404 page the issue is you need to do

Response.TrySkipIisCustomErrors = true;

Before you let the response finish otherwise IIS will intercept the error.

This is completely beyond unintuitive especially if you set the status code yourself. I tried to figure a way to file a bug on Microsoft Connect that manually setting a http error code does not automatically set TrySkipIisCustomErrors but could not seem to figure out any relevant product to submit it to.

Chris Marisic
A: 

I had a similar problem, and a call to Server.ClearError() before the redirect did solve the problem.

In your case I would write

void Application_Error(object sender, EventArgs e) 
{ 
    // Code that runs when an unhandled error occurs 
        Exception objError = Server.GetLastError(); 
        if(objError is HttpException){
          //Need to clear the error, otherwise the buil-in redirect would occure
          Server.ClearError(); 
          Response.Redirect( 
              String.Format( 
              "/Error/{0}/{1}", 
              ((HttpException)objError).GetHttpCode(), 
              Request.RawUrl)); 
        }
} 

Notice that Server.GetLastError().GetBaseException() returns the base exception, which isn't always the HttpException, the one you are looking for is just GetLastError().

jaraics