ASP.NET MVC 3 - Dealing with Session variables
Asked Answered
H

5

7

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

Hopple answered 12/4, 2012 at 12:0 Comment(1)
Is the site running on shared host?Teryl
M
5

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);   
    }
}
Micah answered 10/4, 2013 at 15:28 Comment(1)
this have to be a big warning on tutorials and manuals of Form's Authenticatio / membership on asp.net. thanks for point the best solution so farVoluptuary
R
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"].

Reorganization answered 21/5, 2013 at 21:45 Comment(0)
G
0

The issue you have is with the line

FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

This is a cookie and last longer than sessions (depending on how long you set the forms timeout)

If all you need is to just display the username, you can use and just remove the session altogether

<h3>Welcome, @User.Identity.Name</h3>
Gentilis answered 12/4, 2012 at 12:10 Comment(1)
No, I need to display their real name, I knew I could use their username, but I wanted to display their real name. I've made the cookie expire after the same period in my web.config: <forms loginUrl="~/Account/LogOn" timeout="60" / I also use a session variable in another place on the site and am having the same issue, so I was wondering what causes itHopple
R
0
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 

this code should work fine and you should be able to see "Welcome USERNAME", try to see that whether IE settings like tools-->internet options-->General tab delete my browsing history is checked or not. (on the same tab is you click on delete button you will see its clearing cookies also so that might be issue).

Cookies values will be retained if you close browser but not session(inproc) variables.

Rudd answered 12/4, 2012 at 12:17 Comment(1)
But its not a cookie? Session state is held on the server isnt it? Also I don't want to display the Username as I've stated, thats why I use a method to retrieve the user's actual name and put that into a session variableHopple
N
0

Maybe first check to ensure that a new session isn't started somehow. Place a breakpoint in the Session_Start in the global.asax.cs file:

protected void Session_Start(object sender, EventArgs e)
{
    var sessionId = Session.SessionID; // break here
}

It might seem silly but there are a couple of things that could actually cause a new session. Eliminating those will get you closer to a solution.

Closing your browser and opening it up again will probably cause a new session. Changes to the folder structure within your site and changes to the web.config will cause a new session (application pool will be recycled).

Nicaragua answered 13/4, 2012 at 7:5 Comment(14)
My global.asax file doesnt have a Session_Start methodHopple
Right, instead of that, I did a response.write(session.sessionId) on my index page and the 2 session id's are different.Hopple
Once I've re-opened my browser, If I keep refreshing a new SessionID is generated each time? But If I log in and don't close my browser and then keep hitting refresh, I have the same SessionIDHopple
OK, so somehow your session is being restarted. Your browser cookies may be to blame here since typically a cookie is used to store the session id.Nicaragua
Any idea on how I resolve this, otherwise my only option is to remove the remember me featureHopple
I don't think removing the feature will solve your session problem. You are probably going to want your session not expire. Are your cookies enabled on your browser?Nicaragua
Yea, if they weren't then it wouldnt keep me logged in once I have closed and re-opened the browserHopple
Hang on, your issues isn't with the session expiring. Rather with getting the user name into the Session variable. You can use the session start event to do that. Find your user again and set the Session["Name"] or use a cookie to store the name. lol --- silly that I missed the point.Nicaragua
Well, I have a basket which I use the session variable, along with the user's account number to retrieve the items in their basket. So new session == new basketHopple
Hmm, this doesn't work either, it outputs blank info after moving it to the session start event, I noticed the session start event fired even before I had logged inHopple
That's fine. But a new session means all you session contents are gone. So the Session["Name"] is gone that you set in the logon. You basically have to put that back when the session starts and you have the auth cookie. I don't use FormsAuthentication but if you can retrieve the user name use it to fetch the user from your data store and set the Session["Name'} again.Nicaragua
The session start event will fire as soon as the session is created. Then you move on to other things like logging in, etc. That is why if you are remembered you can pick it up in the session start.Nicaragua
Not if a new session ID is being created, like what's happening in my case at the moment?Hopple
I don't quite understand your question but since every session has a an ID a new session = new ID.Nicaragua

© 2022 - 2024 — McMap. All rights reserved.