我一直在尝试为我的一些类实现一个静态的“Current”属性,使其表现得像 HttpContext.Current 属性。那些仅依赖于上下文或请求标头的行为正常。但是,那些依赖于当前 Session 对象的失败。在这些情况下,Session 对象似乎为空:
// THIS WORKS
private static HttpContext Context { get { return HttpContext.Current; } }
// THIS APPEARS TO YIELD NULL
private static HttpSessionState Session { get { return HttpContext.Current.Session; } }
public static EducationalUnit Current
{
get
{
if (Context.Items["EducationalUnit.Current"] == null)
{
SetCurrent();
}
return (EducationalUnit)Context.Items["EducationalUnit.Current"];
}
set
{
Context.Items["EducationalUnit.Current"] = value;
}
} // Current
// I've tried a few things here, to scope out the status of the Session:
private static void SetCurrent()
{
// shows "null"
throw new Exception(Session);
// shows "null"
throw new Exception(Session.SessionID);
// also shows "null"
throw new Exception(HttpContext.Current.Session);
// shows "Object reference not set to an instance of an object."
throw new Exception(HttpContext.Current.Session.SessionID);
// this, however, properly echos my cookie keys!
JavaScriptSerializer js = new JavaScriptSerializer();
throw new Exception(js.Serialize(Context.Request.Cookies.Keys.ToString()));
} // SetCurrent()
在我的一生中,我无法从 SetCurrent() 方法中获取会话。
有什么想法吗?
谢谢!