Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an existing session in my BaseController constructor

In my Global.asax, i have this code in the 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's working in all of mines controllers who use this base controller but not in my BaseController Constructor himself.

This session is Null...

Have 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 better way?

like image 952
Portekoi Avatar asked Dec 01 '22 20:12

Portekoi


1 Answers

That's normal, all HttpContext related objects such as the Session are not yet initialized in the constructor of an ASP.NET MVC controller. This happens at a later stage, in the Initialize method that you could use:

public BaseController: Controller
{
    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        ViewBag.UserMenu = this.UserIntranet.Login;
    }
}
like image 125
Darin Dimitrov Avatar answered Dec 03 '22 10:12

Darin Dimitrov