ASP.NET MVC 3 - Dealing with Session variables

2019-04-26 03:10发布

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

5条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-26 03:27

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"].

查看更多
我只想做你的唯一
3楼-- · 2019-04-26 03:33
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.

查看更多
我想做一个坏孩纸
4楼-- · 2019-04-26 03:40

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>
查看更多
ゆ 、 Hurt°
5楼-- · 2019-04-26 03:43

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).

查看更多
甜甜的少女心
6楼-- · 2019-04-26 03:47

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);   
    }
}
查看更多
登录 后发表回答