Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if current request is an asynchronous postback, in ASP.NET Application_Error event

Is it possible to determine whether the current request is an asynchronous postback (partial page update) from within the Application_Error event?

What's the best way to handle application errors when asynchronous postbacks are used?

In Application_Error, we are redirecting to different error pages but that doesn't work properly when the error is thrown during an asynchronous postback. We noticed that this holds true even when AllowCustomErrorsRedirect = false and we have an OnAsyncPostBackError handler to set the AsyncPostBackErrorMessage. During asynchronous postbacks, our AsyncPostBackErrorMessage is overwritten and the client receives a generic web page error instead.

like image 463
BlueFox Avatar asked Jan 23 '12 20:01

BlueFox


2 Answers

In the Application_Error method you no longer have direct access to the <asp:ScriptManager> control on the page. So it's too late to handle its AsyncPostBackError event.

If you want to prevent a redirect, you should check the request to see if it is in fact an asynchronous request. The <asp:UpdatePanel> causes a post back with the following HTTP header:

X-MicrosoftAjax:Delta=true

(also see: ScriptManager Enables AJAX In Your Web Apps)

A check for this header would look something like this:

HttpRequest request = HttpContext.Current.Request;
string header = request.Headers["X-MicrosoftAjax"];
if(header != null && header == "Delta=true") 
{
  // This is an async postback
}
else
{
  // Regular request
}

As to what would be an appropriate way to handle the exception is a different question imho.

like image 135
Michiel van Oosterhout Avatar answered Oct 30 '22 11:10

Michiel van Oosterhout


I had a similar scenario. What worked for me was calling Server.ClearError() in my event handler for the ScriptManager's AsyncPostBackError. This prevents the Global.asax Application_Error function from being called.

like image 21
jcj80 Avatar answered Oct 30 '22 11:10

jcj80