JohnMalcom
JohnMalcom

Reputation: 861

How can I save a session variable in the object?

I have the following Session variable: Session["UserId"];

How can I save this variable in the class and public variables? Something like this:

public class UserDC
{
    //public static Session UserId = Session["UserId"] 
}

I only want to call: UserDC.UserId.

Upvotes: 2

Views: 9229

Answers (2)

Josh Mein
Josh Mein

Reputation: 28665

Is this what you are looking for?

public class UserDC
{
    public static string UserId
    {
        get
        {
            if(HttpContext.Current.Session["Test"] != null)
                return HttpContext.Current.Session["Test"].ToString()
            else 
                return "";
        }

        set
        {
            HttpContext.Current.Session["Test"] = value;
        }
    }
}

Edit:

In order to get a Session variable within a static property or static method, you must actually do the following because HttpContext.Current is static:

HttpContext.Current.Session

Upvotes: 6

Wiktor Zychla
Wiktor Zychla

Reputation: 48314

public static string UserId
{
   get
   {
      return (string)Session["UserId"];
   }
}

Upvotes: 0

Related Questions