会话存储与类存储

The*_*kZn 4 c# asp.net class session-variables

我总是在一个Session变量中为用户存储数据(在他们登录后),因此我可以在任何页面上使用该数据.
我发现另一种全局存储信息的方法是将它存储在一个类中,使用{ get; set;},然后从任何页面调用它.

现在,我已经使用这两种方法作为测试,它们都运行得很好:

Session["LoginId"] = rdr["uniqueIdentifier"].ToString();

和

Member.LoginId = rdr["uniqueIdentifier"].ToString();

哪里(在Member.cs中)

public class Member
{
    public static int Challenges { get; set; }
    public static int NicknameId { get; set; }
    public static string LoginId { get; set; }
    public static string FriendsListId { get; set; }

    public static void ClearVariables()
    {
        Challenges = 0;
        NicknameId = 0;
        LoginId = null;
        FriendsListId = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

Global.asax中

void Session_End(object sender, EventArgs e) 
    {
        Member.ClearVariables();
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是,在这样的类中存储用户数据是否足够安全,还是应该坚持使用Session对象?

已更新为完整性 此帖子会执行上述操作,但适用于多个用户? 如何从ASP.NET中的任何类访问会话变量?

Ami*_*ach 8

在你的情况下,它根本不安全,因为asp.net中的静态变量对所有用户都是通用的.


muh*_*hif 8

我发现这种方法是最容易使用和最少机会错误之一.我认为这称为Facade Design Pattern.

 public class SiteSession
{
    #region Attributes
    private static string _siteSession = "__SiteSession__";
    #endregion

    #region Constructor
    private SiteSession()
    {
    }
    #endregion

    #region CurrentSession
    public static SiteSession Current
    {
        get
        {
            SiteSession session = HttpContext.Current.Session[_siteSession ] as    SiteSession;
            if (session == null)
            {
                session = new SiteSession();
                HttpContext.Current.Session[_siteSession ] = session;
            }
            return session;
        }
    }
    #endregion

    #region SessionProperties
    public sherserve.CustomTypes.UserTypes UserType { get; set; }
    public int UserID { get; set; }
    public String StaffID { get; set; }
    public String Position { get; set; }
    public String StaffName { get; set; }
    public int TimeZone { get; set; }

    public String DealerId { get; set; }
    public String DealerPosition { get; set; }
    public String DealerName { get; set; }
    public int DealerFirmId { get; set; }

    public String ClientId { get; set; }
    public String ClientName { get; set; }
    public String ClientBusiness { get; set; }
    public String CountryCode { get; set; }
    public int ClientFirmId { get; set; }
    #endregion

}
Run Code Online (Sandbox Code Playgroud)

值可以像这样存储在Session中:

 SiteSession.Current.UserType = user.UserType;
Run Code Online (Sandbox Code Playgroud)

并且可以这样获得:

int userId=    SiteSession.Current.UserID;
Run Code Online (Sandbox Code Playgroud)

它也是类型安全的.