解决方案一:
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;
}
}
}