Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. So in subsequent requests, we can correctly set the IPrincipal and IIdentity based on the user object in session.

like image 215
Jason Avatar asked Nov 10 '09 00:11

Jason


People also ask

What is the page lifecycle of an ASP.NET MVC?

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.

Which handles the initial step in the ASP.NET MVC request life cycle?

Routing. Asp.net Routing is the first step in MVC request cycle.

Is session available in MVC?

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.


2 Answers

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.

like image 68
tvanfosson Avatar answered Sep 18 '22 12:09

tvanfosson


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

like image 28
bygrace Avatar answered Sep 22 '22 12:09

bygrace