【问题标题】:HttpContext.Current.Session null itemHttpContext.Current.Session 空项
【发布时间】:2011-01-17 06:01:13
【问题描述】:

我将当前用户存储在 HttpContext.Current.Session 中,SiteUser 是呈现当前活动站点用户的单音类,当他登录时,我在控制器和构造函数中创建新的 SiteUser(),并将他添加到会话中:

public static SiteUser Create()
{
    HttpContext.Current.Session[sessionKey] = new SiteUser();

    return HttpContext.Current.Session[sessionKey] as SiteUser;
}

然后,对于服务器服务的每个请求,我都会检查用户是否在会话中可用:

public static SiteUser Current
{
    get
    {
        if (HttpContext.Current.Session == null || HttpContext.Current.Session[sessionKey] == null)
        {
            throw new SiteUserAutorizationExeption();
        }

        return HttpContext.Current.Session[sessionKey] as SiteUser;
    }
}

否则我会生成非身份验证用户异常并将他重定向到登录页面。 但有时 HttpContext.Current.Session[sessionKey] 为空,但 HttpContext.Current.Session 不为空且 FormsAuthenticationTicket 可用且 Expired 属性也为假。 有人可以帮我吗,为什么 HttpContext.Current.Session[sessionKey] 可以为空?

UPD:webconfig 会话设置:<sessionState mode="InProc" timeout="20" />

UPD:sessionKey 为:public const string sessionKey = "SiteUser";

UPD2:我忘了补充,在会话中还存储了文化设置:

HttpContext.Current.Session["Culture"]

当异常发生时,HttpContext.Current.Session[sessionKey] 为 null,culture-item 不是

UPD3:我已经下载了源 .NET Framework 的符号表,并在 SessionStateItemCollection 处设置断点以更改集合项。我解决了一些错误: 1)所有集合项都是空的——“文化”是在之后设置的 2)它发生在会话结束事件 我无法理解它是怎么回事,因为在 web.config 会话超时设置为 20

【问题讨论】:

  • 是内存会话吗?还是配置为持久保存到数据库?另外:IIS 是否可能回收应用程序池?
  • mmm.. 我正在使用 InProc 会话模式,这是否意味着会话在内存中? IIS 是否可能回收应用程序池 - 我不确定,目前我在 asp.net 开发服务器上运行
  • 我不认为开发服务器会回收 - 那是 IIS 的事情
  • 你的问题解决了吗?
  • @Daniel,是的。真正的问题在于 IIS 缓存设置。在高负载下它可以缓存带有会话的cookie

标签: .net asp.net asp.net-mvc-3


【解决方案1】:

sessionKey 可能会发生变化,您可能只需要这样做:

HttpContext.Current.Session["CurrentUser"]

或者会话可能即将到期,请检查超时:

http://msdn.microsoft.com/en-us/library/h6bb9cz9(VS.71).aspx

或者您可能正在从其他地方设置会话值,通常我通过一个属性控制对 Session/Context 对象的访问

static readonly string SESSION_CurrentUser = "CurrentUser";

public static SiteUser Create() {     
 SiteUser.Current = new SiteUser();      
 return SiteUser.Current;
}

public static SiteUser Current {     
 get {         
  if (HttpContext.Current.Session == null || HttpContext.Current.Session[SESSION_CurrentUser] == null) {             
   throw new SiteUserAutorizationExeption();         
  }          
  return HttpContext.Current.Session[SESSION_CurrentUser] as SiteUser;     
 } 
 set {
  if (!HttpContext.Current.Session == null) {
   HttpContext.Current.Session[SESSION_CurrentUser] = value;
  }
 }
} 

【讨论】:

  • 是的,我的 sessionKey 是 const 字符串值。我忘记在主题中添加有关此的信息。我会尝试设置属性,这是个好主意,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 2012-12-20
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多