我在.net4上有一个MVC3应用程序,它的会话在dev环境中工作,但不在生产环境中. 在制作中我记录了sessionID,它在我设置和从会话中获取的时刻是相同的. 当我试图获得会话时,我得到Null Excep
在制作中我记录了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;
}
}
}
