Cannot redirect from Application_Error even after clearing the error

3.7k Views Asked by At

I'm trying to error out more gracefully when a user attempts to upload a file that's too large for the server. However, when I try to capture the error in Global.asax.cs, it seems to skip right past my redirection code. Here's the core of what I have.

protected void Application_Error(object sender, EventArgs e)
{
   HttpContext.Current.ClearError();
   Response.Redirect("CustomErrors.aspx", false);
   Context.ApplicationInstance.CompleteRequest();
}

Everywhere I look the 'answer' seems to be to clear the error, but I've already done that. What else could possibly be going wrong. Any ideas?

3

There are 3 best solutions below

6
On

I've just tried your code and when I raise an unhandled error in Page_Load() of my test page and then attempt to redirect with HttpContext.Current.ClearError() present in the Application_Error() method I receive a

Cannot Redirect after HTTP header have been sent error

Removing this ClearError() method, solves this problem.

If however, I raise the event within an event on the page (i.e. a button click), this works fine even with calling HttpContent.Current.ClearError().

One thing I did notice is you haven't got a '~/' in front of the 'CustomError.aspx', you may want to add this so that the page is found regardless of where the error is raised. (I think I you had multiple folders and an error happens, the context will be in the current folder).

A better way of adding a custom error page is just to modify the web.config with the necessary configuration, this will perform the redirect for you. You can still then log the error (via Log4Net or equivalent) in the Application_Error() method. You may find this question, helpful if you want to display the exception on your custom error page.

From this link

<configuration>
    ...

    <system.web>
        <customErrors mode="RemoteOnly"
                      defaultRedirect="~/ErrorPages/Oops.aspx" />

        ...
    </system.web>
</configuration>
1
On

An alternative is to ensure the following is set.

Response.BufferOutput = true;

This way a response is not sent (including the headers) until the the responce is ready to be sent.

See here.

Server cannot set status after HTTP headers have been sent IIS7.5

0
On

I know this is an older thread but I found a way around this...

In the case below Google bot was passing bad URL characters and I wanted to just redirect to default.

After you trap the error Server.ClearError(); then you can redirect to any page on your site.

void Application_Error(object sender, EventArgs e)
{
    //... other code here....

    var Message = ex.Message.ToLower();
    var RootURL = Common.GetAppPathMasterPages() + "default.aspx";

    if (Message.Contains("does not exist") || Message.Contains("potentially dangerous request"))
    {
        Server.ClearError();
        HttpContext.Current.Response.Redirect(RootURL);
        return;
    }    

}