将数据保存到会话状态并与 Froms Auth 会话保持同步
我想将一些数据保存到会话状态。当用户首次通过表单身份验证登录时,我需要保存这些数据。我需要此会话状态变量具有与表单身份验证票证过期相同的生命周期。有什么方法可以确保这两者保持同步吗?
I want to save some data to the session state. I need to save this data off when a user first logs in via forms authentication. I need this session state variable to have the same lifetime as the forms authentication ticket expiration. Is there some way to ensure that these two stay synchronized?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两者在 web.config 中都有一个超时值,您可以将其设置为相同的值。现在这就是你的问题可能开始的地方。表单身份验证 cookie 可能具有滑动过期设置,而会话则没有。因此,如果您希望两个超时值匹配,请确保禁用身份验证 cookie 的滑动到期时间。而这仅仅是开始。对于会话,您可以选择存储它的位置:Off、InProc、StateServer、SqlServer。
当您使用 Off(我个人使用的)时,ASP.NET 会话将被禁用,并且您基本上没有任何会话。
当您将其设置为 InProc(这是默认值)时,会话将存储在内存中。除了 IIS 可以决定在不同情况下回收 AppDomain:一段时间不活动、达到一定的 CPU/内存阈值……这基本上意味着,如果会话存储在内存中并且 AppDomain 被 Web 服务器卸载,您将丢失此会话中存储的所有内容,而显然身份验证 cookie 仍然有效。
StateServer 和 SQLServer 是两种不同的进程外会话存储模式,其中信息不再存储在 Web 服务器的内存中,并且可以在 AppDomain 被回收时继续存在。
基本上总结起来,以可靠的方式同步 ASP.NET 会话生命周期和 ASP.NET 表单身份验证 cookie 生命周期是非常困难的。我通过根本不使用 ASP.NET 会话来解决这个问题。
Both have a timeout value in web.config that you can set to the same value. Now this being said here's where your problems might start. A forms authentication cookie might have a sliding expiration setup whereas a session not. So make sure you disable this sliding expiration for the authentication cookie if you want the two timeout values to match. And that's just the beginning. For the session you can choose where to store it: Off, InProc, StateServer, SqlServer.
When you use Off (personally what I use) ASP.NET session is disabled and you basically don't have any session.
When you set it to InProc (which is the default value) the session is stored in memory. Except that IIS could decide to recycle the AppDomain under different circumstances: a period of inactivity, certain CPU/memory threshold is reached, ... This basically means that if the session is stored in memory and the AppDomain is unloaded by the web server you loose everything stored in this session whereas, obviously, the authentication cookie continues to be valid.
StateServer and SQLServer are 2 different modes of out of process session storage where the information is no longer stored in the memory of the web server and can survive AppDomain being recycled.
So basically to sum up it is very difficult to synchronize in a reliable manner the ASP.NET session lifecycle and the ASP.NET forms authentication cookie lifecycle. I solve this problem by not using ASP.NET session at all.