My question is essentially the same as question 765054 on StackOverflow. I'm only asking it again because the accepted answer is incorrect (you can not access the session object in Application_BeginRequest).
Our use case is that we want to store the authenticated user's user object in the session. So in subsequent requests, we can correctly set the IPrincipal and IIdentity based on the user object in session.
MVC actually defined in two life cycles, the application life cycle, and the request life cycle. The Starting point for every MVC application begins with routing. After that, the received request figures out and finds how it should be handled with the help of the URL Routing Module.
Routing. Asp.net Routing is the first step in MVC request cycle.
By default, Asp.Net MVC support session state. Session is used to store data values across requests. Whether you store some data values with in the session or not Asp.Net MVC must manage the session state for all the controllers in your application that is time consuming.
I do similar things using a base controller and overriding OnActionExecuting. Whether this is the earliest it can be done or not, I don't know, but I do know that it will happen before your action is executed (and thus before the view is rendered). Alternatively you might want to have a custom authorize attribute that does what you want. This might be the only way to make sure that it's done prior to other attributes running.
Apparently AcquireRequestState is the earliest event where HttpContext.Current.Session is not null. I just attached to all of them in sequence and tested. I prefer to use PreRequestHandlerExecute which occurs before the constructor on my controller is called.
This is relevant if you would rather have your code in or referenced from the Global.asax instead. See this page for the sequential list of the events in the application lifecycle: http://msdn.microsoft.com/en-us/library/ms178473%28v=vs.100%29.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With