ASP.NET MVC 3 - Dealing with Session variables

CallumVass picture CallumVass · Apr 12, 2012 · Viewed 20.9k times · Source

I have an app which uses Form's Authentication and when the user log's in, I retrieve the user's actual name and assign that to a session variable, like so:

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            Session["Name"] = client.GetName(model.UserName);
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return RedirectToAction("Index", "Home"); 
        }
    }
}

This is then displayed on my Index view, like so:

<h3>Welcome, @Session["Name"]</h3>

So if my name was Bob, it would output "Welcome, Bob" on my view and this works fine. But once I navigate away from the page or close my browser and return a few minutes later, it seems as if these Session variables have been destroyed as it just outputs "Welcome, " but I'm still logged in so my session isnt destroyed? I've set the session to be destroyed after 60 minutes in my web.config:

<sessionState regenerateExpiredSessionId="true" timeout="60" />

Edit

This only happens when I check my "Remember Me" box when logging in, as I guess this keeps a cookie client side so when I re-open my browser Im still logged in but a new session ID is created as I did a Response.Write(Session.SessionID) on my Index page and the ID before I closed my browser was different to the one when I re-opened it. If I don't check my "Remember Me" box then I'm forced to login again upon re-opening my browser

Answer

dklomparens picture dklomparens · Apr 10, 2013

I had the same problem with my session variables. If the remember me option was selected at the logon it would bypass my code to set the session variable I needed the next time the user would go to the site.

I was able to solve my issue by repopulating the session variable if the IsAuthenticated was true.

protected void Session_Start(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        Session["Name"] = client.GetName(User.Identity.Name);   
    }
}