ASP.NET MVC 3 - Dealing with Session variables
Solution 1
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);
}
}
Solution 2
Instead of adding the name to a session variable, just change the following
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
to
FormsAuthentication.SetAuthCookie(client.GetName(model.UserName), model.RememberMe);
You can then just use the User.Identity.Name instead of the @Session["Name"].
CallumVass
Updated on May 22, 2020Comments
-
CallumVass almost 4 years
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