加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.NET MVC – Session为null

发布时间:2020-12-16 09:26:58 所属栏目:asp.Net 来源:网络整理
导读:我在.net4上有一个MVC3应用程序,它的会话在dev环境中工作,但不在生产环境中. 在制作中我记录了sessionID,它在我设置和从会话中获取的时刻是相同的. 当我试图获得会话时,我得到Null Exception. 这是我访问会话的方式: public static class HandlersHttpStora
我在.net4上有一个MVC3应用程序,它的会话在dev环境中工作,但不在生产环境中.
在制作中我记录了sessionID,它在我设置和从会话中获取的时刻是相同的.

当我试图获得会话时,我得到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是相同的,生产中的行为也不同于开发.

解决方法

解决方案1:

链接: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:

链接:HttpContext.Current.Session null item

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;
  }
 }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读