全局范围内的 .NET 会话替代方案
简单问题:是否有一个“每用户”数据存储对象(类似于Session
),我可以在全局范围内存储数据(类似于HttpRuntime.缓存
)?几乎就像 Session
和 HttpRuntime.Cache
生了一个孩子。
完整背景:我有一个 ASP.NET 网站,最初是为单线程编写的。现在我更改了它,以便某些操作将生成后台线程,并且浏览器轮询服务以获取状态更新。
我遇到的问题是某些数据存储在 HttpContext.Session[] 对象中(例如成员身份验证令牌)。这些数据对于每个用户来说都是唯一的,并且可以被后台线程访问。会话不可用于后台线程。
我知道 HttpRuntime.Cache ,但这需要微观管理来分割用户并在会话过期的同时使其过期。另一方面,Session
会在我也想要的正确时间自动使这些东西过期,并且已经被 SqlMembershipProvider
之类的东西使用。
我的问题是,是否有一些行为类似于 Session 但存在于全局范围内的东西?
Quick question: Is there a "per-user" data storage object (similar to Session
) that I can store data in the global scope (similar to HttpRuntime.Cache
)? Almost as if Session
and HttpRuntime.Cache
had a baby.
Full Background: I have a ASP.NET website that was originally written for a single thread. Now I changed it so that certain actions will spawn a background thread and the browser polls a service to get status updates.
The problem I am having with this is that certain pieces of data are stored into the HttpContext.Session[] object (membership authentication token, for example). These pieces of data need to be unique to each user and accessible to the background thread. Session is not available to the background thread.
I am aware of HttpRuntime.Cache
but that would require micromanagement to segment out the users and to expire it at the same time the session is expired. Session
, on the other hand, automatically expires this things at the right times that I want it too and is already used by things like the SqlMembershipProvider
.
My question is, is there something that behaves similar to the Session but exists in the global scope?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为没有像您需要开箱即用的东西。不过,我会执行以下操作:
I don't think there is anything like you need out of the box. I would do the following though:
Dictionary
or some object list in the value for the user. Use this to store all the data you require.尝试将 HttpContext.Current 对象传递给后台线程上的方法。您应该能够通过
currentContext.Session
从后台线程访问会话,假设currentContext
是传入的HttpContext
参数。请参阅此关于如何从多个线程安全访问 HttpContext 对象的博客文章。
Try passing the
HttpContext.Current
object to the method on your background thread. You should be able to access the session from the background thread throughcurrentContext.Session
assumingcurrentContext
is theHttpContext
parameter that was passed in.See this blog post on how to safely access the HttpContext object from multiple threads.
不会。
因为当应用程序池重新启动时,所有后台活动都会消失,我建议考虑将用户的状态移动到您自己的数据库或外部存储中。不幸的是,您将失去自动会话管理的好处(滑动过期),但如果您需要后台活动,它会工作得更好 - 即,如果稍后需要,您将能够将活动从 IIS 进程移至单独的进程/机器。
No.
Since when application pool restarts all backgound activity die I suggest to think about moving user's state to your own database or external storage. Unfortunately you'll lose automatic session management benifits (sliding expiration), but if you need backgound activity it will work better - i.e. you'll be able to move your activity out of IIS process to separate process/machine if needed later.