get返回null

时间:2012-11-04 18:40:19

标签: c# .net

我有一些课

public static class SessionManager
{
    public static UserSession UserSession
    {
        set
        {                
           HttpContext.Current.Session["USER_SESSION"] = value;
        }
        get
        {
           UserSession userSession = new UserSession();

           try
           {
              userSession = (UserSession)HttpContext.Current.Session["USER_SESSION"];
           }
           catch (Exception)
           {
           }

           return userSession;
       }
   }
}

我正在尝试使用它

var userSession = SessionManager.UserSession;

userSesssion始终是null

有任何解决方法吗?

3 个答案:

答案 0 :(得分:1)

试试这个:

userSession = (UserSession)(HttpContext.Current.Session["USER_SESSION"]);

-OR -

userSession = HttpContext.Current.Session["USER_SESSION"] as UserSession;

答案 1 :(得分:1)

我认为你在房产中实际寻找的模式看起来更像是这样:

public static class SessionManager
{
    public static UserSession UserSession
    {
        set
        {                
           HttpContext.Current.Session["USER_SESSION"] = value;
        }
        get
        {
            var session = HttpContext.Current.Session;
            var userSession = session["USER_SESSION"] as UserSession;

            if (userSession == null)
            {
                userSession = new UserSession ();
                session["USER_SESSION"] = userSession;
            }

            return userSession;
        }
    }
}

(我只突破了var session = HttpContext.Current.Session;所以它在StackOverflow中都很合适。)

答案 2 :(得分:0)

我找到了解决方案......

我忘了在Global.asax.cs下插入

void Session_Start(object sender, EventArgs e)
        {
            var userSession = new UserSession();

            SessionManager.UserSession = userSession; 

        }