When is the earliest I can access SESSION in the ASP.NET MVC page lifecycle?
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. S开发者_如何转开发o in subsequent requests, we can correctly set the IPrincipal and IIdentity based on the user object in session.
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
精彩评论