繁体   English   中英

在ASP.Net中为不同的会话变量设置不同的超时

[英]Set different timeout for different session variables in ASP.Net

这是否可以为ASP.Net中的不同会话设置不同的超时?

编辑我的意思是在同一页面我有2个会话变量Session [“ss1”]和Session [“ss2”],是否有可能为每个会话设置超时? 或者无论如何都要像保存会话到cookie并设置过期一样? 我刚刚接触ASP.Net新手

我写了一个非常简单的扩展类来做到这一点。 你可以在这里找到源代码

用法:

//store and expire after 5 minutes
Session.AddWithTimeout("key", "value", TimeSpan.FromMinutes(5));

在登录时设置任何超时,您可以为不同的用户设置不同的超时...

HttpContext.Current.Session.Timeout = 540;
/// <summary>
/// this class saves something to the Session object
/// but with an EXPIRATION TIMEOUT
/// (just like the ASP.NET Cache)
/// (c) Jitbit 2011. MIT license
/// usage sample:
///  Session.AddWithTimeout(
///   "key",
///   "value",
///   TimeSpan.FromMinutes(5));
/// </summary>
public static class SessionExtender
{
  public static void AddWithTimeout(
    this HttpSessionState session,
    string name,
    object value,
    TimeSpan expireAfter)
  {
    session[name] = value;
    session[name + "ExpDate"] = DateTime.Now.Add(expireAfter);
  }

  public static object GetWithTimeout(
    this HttpSessionState session,
    string name)
  {
    object value = session[name];
    if (value == null) return null;

    DateTime? expDate = session[name + "ExpDate"] as DateTime?;
    if (expDate == null) return null;

    if (expDate < DateTime.Now)
    {
      session.Remove(name);
      session.Remove(name + "ExpDate");
      return null;
    }

    return value;
  }
}
Usage:

//store and expire after 5 minutes
Session.AddWithTimeout("key", "value", TimeSpan.FromMinutes(5));

//get the stored value
Session.GetWithTimeout("key");

亚历克斯 CEO,创始人https://www.jitbit.com/alexblog/196-aspnet-session-caching-expiring-values/

如果您正在讨论不同用户的会话超时,那么您可以使用Global.asax ,您可以使用Session_Start事件,在这种情况下,您可以为不同的用户设置不同的会话超时

答案是没有会话超时适用于每个用户的所有会话变量。 但是,您可以使用缓存或cookie,它们都支持单个(每个键)级别的超时。

但坚持这些解决方案并非没有一些重大缺点。 如果使用缓存,则会丢失会话提供的隐私,如果使用cookie,则会受到文件大小和序列化问题的限制。

一种解决方法是使用缓存并确保在您使用的每个密钥中包含用户的会话ID。 这样,您最终会得到一个模仿会话本身的缓存存储。

如果您想要进一步的功能并且不想打扰实现它,那么您可以使用CodePlex上这个小项目的API:

http://www.univar.codeplex.com

2.0版本提供了许多开箱即用的存储类型选项,包括会话绑定缓存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM