1

在我的 ASP.NET MVC 3 应用程序中,当我在我的登录操作中选中我的记住我框时,它应该创建一个持久 cookie,这样当我关闭浏览器并重新打开它时,我仍然应该登录:

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

当我使用 Fiddler 时,我可以看到会话 ID 是这样发送的:

Request sent 342 bytes of Cookie data:

ASP.NET_SessionId=<Session ID>; .ASPXAUTH=<Auth String>

但是当我关闭浏览器并重新打开它时,我仍然登录但请求没有发送会话 ID:

Request sent 298 bytes of Cookie data:

.ASPXAUTH=<Auth String>

然后Response.Write(Session.SessionID)我输入我的操作,每次我重新打开浏览器后刷新页面时都会更改。如果我不关闭浏览器,那么每次刷新的会话 ID 都保持不变。

我正在使用StateServer来保存会话状态,因为我认为这可能会解决问题,因为我也经历过InProc.

4

1 回答 1

3

That's expected behavior. The concept of setting an authorization cookie, and the concept of sessions are not the same thing. A session in ASP.NET is meant to live as long as the user has their browser open, because a session is stored in a per-session cookie.

"...the SessionID value is stored in a non-expiring session cookie in the browser. (http://msdn.microsoft.com/en-us/library/ms178581.aspx)

Having a persistent session is sort of a bad idea. Remember, the normal case for Sessions is that they are stored in memory. Would you really want to save the session of users in memory who haven't logged in in a week? Any sort of "session" data you are trying to save that long should not be stored in a session, but in a persistent data store (read: database).

Updated based on your comment

Might I suggest you do something like this:

public string GetMyCompany(){
  return Session["MyCompany"] = Session["MyCompany"] ?? GetMyCompanyFromDatabase();
}
于 2012-04-20T13:41:57.143 回答