Get existing session in my BaseController constructor

In my Global.asax, I have this code in Session_Start ():

UserIntranet user = new UserIntranet(); user.Login = this.Request.LogonUserIdentity.Name.Split('\\')[1]; Session["user"] = user as UserIntranet; 

In my BaseController, I have this property:

 public UserIntranet UserIntranet { get { return Session["user"] as UserIntranet; } } 

It works in all mine controllers that use this base controller, but not in my main BaseController constructor.

This Null Session ...

Try this in my BaseController:

 public BaseController() { ViewBag.UserMenu = this.UserIntranet.Login;/* Null */ } 

Why? How can I get the user login directly in my BaseController? What is the best way?

+4
source share
1 answer

This is normal; all related HttpContext objects, such as Session , are not yet initialized in the ASP.NET MVC controller constructor. This happens at a later stage, in the Initialize method, which you can use:

 public BaseController: Controller { protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); ViewBag.UserMenu = this.UserIntranet.Login; } } 
+18
source

Source: https://habr.com/ru/post/1497045/


All Articles