ASP.NET MVC - 会话为空

2024-04-04

我在 .net4 上有一个 MVC3 应用程序,其会话在开发环境中工作,但不在生产环境中工作。
在生产中,我记录了会话 ID,然后在我从会话中设置和获取时它是相同的。

当我尝试参加会议时,我得到了Null Exception.

这是我访问会话的方式:

public static class HandlersHttpStorage
{
    public static string TestSession
    {
        get
        {
            return HttpContext.Current.Session["time"];//This is null
        }
        set
        {
            HttpContext.Current.Session.Add("time", value);//DateTime.Now.ToString()
        }
    }
}

让我担心的是,生产中的行为与开发中的行为不同,即使 web.config 是相同的。


解决方案一:

Link: 路由请求时 HttpContext.Current.Session 为 null https://stackoverflow.com/questions/218057/httpcontext-current-session-is-null-when-routing-requests

知道了。事实上,很愚蠢。在我删除并添加 SessionStateModule 后它就起作用了,如下所示:

<configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

简单地添加它是行不通的,因为“Session”应该已经在machine.config.

现在,我想知道这是否是通常的做法。看起来肯定不是这样,因为它看起来很粗糙......

解决方案2:

Link: HttpContext.Current.Session 空项目 https://stackoverflow.com/questions/4710411/httpcontext-current-session-null-item

sessionKey 可能会发生变化,您可能只需要执行以下操作:

HttpContext.Current.Session["CurrentUser"]

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

http://msdn.microsoft.com/en-us/library/h6bb9cz9(VS.71).aspx 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;
  }
 }
} 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET MVC - 会话为空 的相关文章

随机推荐