Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session null in ASP.Net MVC Controller Constructors

Why is Session null in the constructors of Controllers? It can be accessed from Action methods. Presumably, because the MVC Routing framework is responsible for newing-up a Controller, it just hasn't (re-)instantiated the Session at that point.

Does anyone know if this is by design and, if so, why?

[I have managed to circumvent the problem by using a Lazy Loading Pattern.]

like image 745
Chris Arnold Avatar asked May 20 '09 18:05

Chris Arnold


People also ask

Why HttpContext current session is null?

Session will never be null if you have any variable in the Session. HttpContext. Current. Session represents a collection of all the session values that you are storing in the session.


2 Answers

Andrei is right - it is null because when running under the ASP.NET MVC framework, the HttpContext (and therefore HttpContext.Session) is not set when the controller class is contructed as you might expect, but it set ("injected") later by the ControllerBuilder class. If you want a better understanding of the lifecycle you can either pull down the ASP.NET MVC framework (the source is available), or refer to: this page

If you need to access the Session then one way would be to override the "OnActionExecuting" method and access it there, as it will be available by that time.

However, as Andrei is suggesting, if your code is reliant on the Session then it could potentially be difficult to write unit tests, so perhaps you could consider wrapping the Session in a helper class which can then be swapped out for a different, non-web version when running under unit tests, therefore de-coupling your controller from the web.

like image 178
Andrew W Avatar answered Sep 23 '22 08:09

Andrew W


In addition to the other answers here, while Controller.Session is not populated in the constructor, you can still access the session through:

System.Web.HttpContext.Current.Session

with the standard caveat that this potentially reduces your controller's testability.

like image 23
Mike Chamberlain Avatar answered Sep 20 '22 08:09

Mike Chamberlain