4

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?

Portekoi
  • 1,087
  • 2
  • 22
  • 44

1 Answers1

19

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;
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • What do you mean? Override the method? But how can i get this existing session? Can you give me an example? – Portekoi Aug 14 '13 at 14:34
  • 1
    Sure, I have updated my answer with an example. Don't try to use the Session in the constructor of the controller, you should override the `Initialize` method and you could use the session in there. – Darin Dimitrov Aug 14 '13 at 14:35
  • You're my hero :) Thanks a lot ! – Portekoi Aug 14 '13 at 14:37