We developed web application using Asp.Net Framework 2.0, AJAX and VS 2005. Later after launch of VS 2008 and .Net Framework 3.5 we ported application to Asp.Net Framework 3.5. As needed we also upgraded AJAX toolkit which is compliant to Asp.Net 3.5. And this causes the problem as follows:
In our application we are handling error as follows:
- If exception occurs in normal (synchronous) request then we redirect user to generic Error Page. This code is written in Global.asax page in Application_Error event.
- If exception occurs in asynchronous request then we let AJAX Framework handle that error in its "
In case Asp.Net 2.0 and AJAX, when any exception thrown while execution of asynchronous request, it is catched in "
ScriptManager1_AsyncPostBackError" event, then AJAX framework handles that exception and shows java script alert box to user. No event (
Application_Error) from Global.asax file gets fired.
But, in Asp.Net 3.5 AJAX they changed exception handling mechanism and now both events "
Application_Error from Global.asax gets fired.
Redirect is not allowed in asynchronous request. Ha.... exception within Application_Error method ;).
Application_Error method from Global.asax, check request is of which type. If it is of asynchronous then don't redirect to generic Error Page else redirect to generic Error Page. (Simple one right!!)
But, How to check Request is of type synchronous or asynchronous in Global.asax?
- There is no related property in
- There is one property called
ScriptManager class but we can not browse it as it has attribute
- Also, you can not access ScriptManager in Global.asax :).
If you check code for setting
IsInAsyncPostBack (which we can not browse) property using reflector, it looks like
It is calling
IsAsyncPostBackRequest method from
PageRequestManager class (which is internal sealed class). So, we can not inherit or extend it. Then what should we do?
ADD EXTENSION METHOD : This is the solution.
So, what we did we added one extension method in
HttpRequest class which does the job. Some details and example of extension method you can find here.
Some thumb rules for adding extension method are:
- It should be static method within static class.
- The this keyword should be in front of parameter.
Here is method implementation which looks like:
Now, this method is part of
HttpRequest class, so you can use it like any other methods of
Using the code
Here, is code snippet which uses this extension method (this is from Global.asax):
So, now we can check if request is not of type asynchronous then only redirect to generic Error Page. PROBLEM SOLVED !!
Using this way now you can check whether request is synchronous or asynchronous anywhere in application.
Points of Interest
We quite often come across situation where we need to check request is synchronous or aynchronous. Strange: ASP.Net does not provide this in Framework.