C# ASP.NET MVC 3 - 处理会话变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10123143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC 3 - Dealing with Session variables
提问by CallumVass
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:
所以如果我的名字是鲍勃,它会在我的视图中输出“欢迎,鲍勃”,这很好用。但是一旦我离开页面或关闭浏览器并在几分钟后返回,这些会话变量似乎已被破坏,因为它只输出“欢迎”,但我仍然登录,所以我的会话没有被破坏?我已在 web.config 中将会话设置为在 60 分钟后销毁:
<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
这只发生在我登录时选中“记住我”框时,因为我猜这会保留一个 cookie 客户端,所以当我重新打开浏览器时,我仍然登录但创建了一个新的会话 ID,就像我Response.Write(Session.SessionID)在我的关闭浏览器之前的索引页面和ID与我重新打开浏览器时的不同。如果我没有选中“记住我”框,那么在重新打开浏览器时我将被迫再次登录
采纳答案by dklomparens
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.
如果 IsAuthenticated 为真,我能够通过重新填充会话变量来解决我的问题。
protected void Session_Start(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
Session["Name"] = client.GetName(User.Identity.Name);
}
}
回答by Jason Jong
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)
这是一个 cookie,持续时间比会话长(取决于您设置表单超时的时间)
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>
回答by ParikshitSehgal
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-->Generaltab delete my browsing historyis 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).
这段代码应该可以正常工作,您应该能够看到"Welcome USERNAME",尝试查看是否检查了tools-->internet options-->General选项卡等 IE 设置 delete my browsing history。(在同一个选项卡上,您单击删除按钮,您也会看到它正在清除 cookie,因此这可能是问题)。
Cookies values will be retained if you close browser but not session(inproc) variables.
如果您关闭浏览器而不是 session(inproc) 变量,则 cookie 值将被保留。
回答by Eben Roux
Maybe first check to ensure that a new session isn't started somehow. Place a breakpoint in the Session_Startin the global.asax.csfile:
也许首先检查以确保没有以某种方式启动新会话。Session_Start在global.asax.cs文件中放置一个断点:
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).
关闭浏览器并再次打开它可能会导致新的会话。对站点内文件夹结构的更改以及对 web.config 的更改将导致新会话(应用程序池将被回收)。
回答by Remy
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"].
然后您可以只使用 User.Identity.Name 而不是 @Session["Name"]。

