0

我有一些课

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

任何线索如何解决?

4

3 回答 3

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。)

于 2012-11-04T19:01:14.323 回答
1

尝试这个:

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

-或者-

userSession = HttpContext.Current.Session["USER_SESSION"] as UserSession;
于 2012-11-04T18:46:20.120 回答
0

I found solution...

I just forgot to insert under Global.asax.cs

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

            SessionManager.UserSession = userSession; 

        }
于 2012-11-04T18:49:58.750 回答