ASP.NET global.asax usage - asp.net

When to use and not to use global.asax file in asp.net application? I heard that you should use that file only at a pinch.

The Global.asax file is used to implement application and session level events, such as:
Application_Init - fired when an application first initializes
Application_Start - fired when the application first starts
Application_End - the final event fired when the application ends or times out
Session_Start - fired the first time a user’s session is started
Application_BeginRequest - fired with each new request
Application_EndRequest - fired when the application ends
Application_AuthenticateRequest - the event indicates that a request is ready to be authenticated.
Application_Error - fired when an unhandled error occurs within the application
Session_End - fired whenever a single user Session ends or times out.
Implementing these handlers can all be legitimate uses of the global.asax. For example, the Application_Error event handler typically logs any global errors, and the Application_End event handler typically contains application cleanup logic. These are good uses of the Global.asax. Use them whenever necessary, and don't be afraid if the file grows.
However, I have seen cases where developers have added all sorts of global methods to the global.asax that are indeed un-justified. For example, keep business logic related to a particular domain object inside the object itself rather than in the global.asax. If you find methods in the Global.asax that shouldn't be there refactor the work into the right location.

global.asax is a HTTPModule. All requests go through the global.asax and other modules before they reach your page handlers. Use this to perform certain tasks on your request or response, like url routing, global error handlign etc.

If you need something special to happen on Application start/end or Session start/end, or globally handle exceptions you could use it to map the events in the Apllication and Session life cycles.

Related

After session timeout ASP.NET not executing Session_Start before invoking new MVC Action

I have some logic as part of Session_Start method in Global.asax.cs file.
the logic loading some information from the database to session variable so all other Controller actions can use them. Everything if working fine until the session expire.
Since i am using Angular (SPA), users actions not goes to the server frequently so the session can just expire after 20 minutes of "server inactivity" (Its not inactivity of the user because he it working on the client side).
Once he want to perform an action that needs to execute a MVC controller action, the controller constructor doesn't find the information on the cache and throws an error.
I expected that the Session_Start will triggered before invoking the controller contractor but the Sesion_Start event not firing at all because i am not assigning information to the session variables, i need only to read them but they are not available.
i tried to assign a dummy data to the session in order to fire the Session_Start event but i can do so only from the controller action but i need the session_start event will be executed BEFORE the Controller constructor.
Is there a way to trigger Session_Start on EVERY server request when the session is not exist (expired)? Is there an option to fire it before the controller constructor?
the problem is that i can not do so from Application_BeginRequest() for example because sessions can not be accessed or use at that scope.
*** This problematic behavior happens only in production. on dev the session_start always fire. i understand its "by design" so it a bit hard to reproduce **

Application_Start Vs Session_Start

Actually I am new to ASP.NET and I came through these concepts.
What is the difference between Application_Start Vs Session_Start?
And also how to know how many users are currently active in our application? Is by using Application_Start or by using Session_Start?
Application_Start executes just once when the application/worker process starts or IIS restarts. You can instantiate application variables, for example.
Session_start executes each time a Session is created, such as to instantiate and manage visitor data.
Application_Start Method is Fired on When the Application Started
Application_Start runs once before Files are Processed
Where
Session_Start Method is Fired at the beginning of each session.
Session_Start runs at the starts of each unique user session.

Is Global.asax Application_Error async?

I need to handle requested file missing with complex longworking logic.
I can do it in Application_Error but not sure if it is async itself or not?
Will this handler block other users for all time, if it take for example 5 minutes or more to work?
The Application_Error its take part of the page processing, is called from the page that you load, so the question is if the Page or the handler is asynchronous its self.
It is, if you not use session, and of course if you do not use other synchronization locks, like mutex, or database open/read/write
Why is that ? because session is locking the full processing, look at this question/answer:
call aspx page to return an image randomly slow
ASP.NET Server does not process pages asynchronously
Trying to make Web Method Asynchronous
Web app blocked while processing another web app on sharing same session  
What perfmon counters are useful for identifying ASP.NET bottlenecks?  
Replacing ASP.Net's session entirely  
File upload and result pooling kills ASP.NET web app
So to make it simple, the Application_Error is just a static function call but is connected to the processing of the page or the handler. Make sure that the page or the handler are not block each other, and all is ok.
From the other hand, a processing of 5 minutes, if you try to make 500 of them together and not place them on a query list, you may have other problems.
I just make a simple test, place System.Threading.Thread.Sleep(20000); on Application_Error and make an error, and continues to load other pages, and works.

What code whould be placed in the application_start and the session_start events in global.asax?

Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
I know when each subroutine is called.
Application_Start when the first user first accesses the web application.
Session_Start when a user opens a session with the application.
But what code belongs in each of these subroutines. What should the code in each subroutine do?
Just any examples? Well, in an MVC site the routes are registered in Application_Start. That's also a good place to initialize an IoC container such as StructureMap. Maybe initialize some singletons you have in your application if you want them to be readily available rather than late-bound when a user accesses them (like if they have a high initialization cost and you'd rather do one slow initial hit on the website yourself than bother a customer or two with it).
Session_Start is generally used less often, but could be a good place for per-user (or per-session, realistically) tracking of some kind.
Application_Start is often used to initialize application wide settings which need to be done once per application domain like registering object containers, reading some config initialization values, ... In Session_Start you could place some code which is tied to the specific user who started the session.
Be careful with exception handling in Application_Start. In IIS7 Integrated mode you won't have the response object or HTTPContext. See this thread: Request is not available in this context

When's the earliest i can access some Session data in global.asax?

i want to check if the Session contains some key/value data, in my global.asax. I'm not sure when the earliest possible time (and method name) is, to check this.
thanks :)
I always believed Application_AcquireRequestState was the first event in Global.asax that could access the current session. It's definitely not Application_BeginRequest.
MSDN casually mentions that the session state is acquired during Application_PostAcquireRequestState event. I wish it was restated at the Life Cycle Overview page.
The latest you can access session state is in Application_PostRequestHandlerExecute, as it is saved by SessionStateModule during the next event Application_ReleaseRequestState.
You need to use BeginRequest (http://msdn.microsoft.com/en-us/library/system.web.httpapplication.beginrequest.aspx) as it is the first event fired on the HttpApplication object (which the Global.asax inherits).
You'll see more about the ASP.NET Application Lifecycle here - http://msdn.microsoft.com/en-us/library/ms178473.aspx (this is for IIS 5 & IIS 6).
According to link text, the earliest events in global.asax that you can access session objects is when global.asax fires Session_Start event
Session__Start: Fired when a new user visits the application Web site.
Session__End: Fired when a user's session times out, ends, or they leave the application Web site

Resources