如何在对象中保存会话变量?

Joh*_*com 2 c# asp.net session

我有以下Session变量: Session["UserId"];

如何在类和公共变量中保存此变量?像这样的东西:

public class UserDC
{
    //public static Session UserId = Session["UserId"] 
}
Run Code Online (Sandbox Code Playgroud)

我只想打电话:UserDC.UserId.

Jos*_*ein 6

这是你想要的?

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

为了在静态属性或静态方法中获取Session变量,您必须实际执行以下操作,因为它HttpContext.Current是静态的:

HttpContext.Current.Session
Run Code Online (Sandbox Code Playgroud)