【问题标题】:Using session to get/set object properties everytime每次使用会话获取/设置对象属性
【发布时间】:2012-05-04 03:48:27
【问题描述】:

我尝试搜索此内容,但我什至不知道如何用它来搜索。

我试图做的是有一个类,每次我访问它来更改它时,我都会从会话中获取和设置值。

这是我正在尝试做的事情(到目前为止我所做的事情。):

public class example
{
   public int prop1 {get;set;}

   public static example Instance
   {
       return (example)(HttpContext.Current.Session["exampleClass"] ?? new example());
   }

}

public class main
{
   protected void Page_Load(object sender, EventArgs e)
   {
      example.Instance.prop1 = "aaa"; //stores value into session
      txtInput.Text = example.Instance.prop1; //retrieves value from session
   }
}

我希望这对我正在尝试做的事情有意义。

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 您的问题是什么?是你没有为你工作吗?
  • 正确。它似乎根本不起作用。我把我的代码放在那里是因为我认为我在正确的轨道上,但是任何其他方式来完成我正在尝试做的事情都是非常受欢迎的。
  • 您需要在第一次将会话变量设置为您的新实例,为您提交解决方案

标签: c# asp.net session


【解决方案1】:

使用泛型很容易做到这一点。

试试这个。

public class Session
{
    public User User
    {
        get { return Get<User>("User"); }
        set {Set<User>("User", value);}
    }

    /// <summary> Gets. </summary>
    /// <typeparam name="T"> Generic type parameter. </typeparam>
    /// <param name="key"> The key. </param>
    /// <returns> . </returns>
    private T Get<T>(string key)
    {
        object o = HttpContext.Current.Session[key];
        if(o is T)
        {
            return (T) o;
        }

        return default(T);
    }

    /// <summary> Sets. </summary>
    /// <typeparam name="T"> Generic type parameter. </typeparam>
    /// <param name="key">  The key. </param>
    /// <param name="item"> The item. </param>
    private void Set<T>(string key, T item)
    {
        HttpContext.Current.Session[key] = item;
    }
}

【讨论】:

    【解决方案2】:

    看起来您已经很接近了,但是您没有任何东西可以将对象实际存储在会话中。试试这样的:

    public static Example Instance
    {
        get
        {
            //store the object in session if not already stored
            if (Session["example"] == null)
                Session["example"] = new Example();
    
            //return the object from session
            return (Example)Session["example"];
        }
    }
    

    这基本上只是Singleton Pattern 的网络友好实现。

    【讨论】:

    • 每次创建Example 的新实例不是很浪费,即使您已经在会话中拥有它?
    • 感谢您的回复!但是有一个问题,我们不应该每次都将它存储在会话中,而不仅仅是当会话为空时吗?我只是在想,如果我用你的解决方案更新会话两次,它就不会第二次保存到会话,对吧?
    • @KrisIvanov:有点浪费,但不是非常浪费。无论如何,这只是为了演示。归根结底,这将取决于对象有多大。
    • @JMD:不,您不需要每次都将它存储在会话中。当您从会话中返回对象时,对其成员的任何更改都将保留。
    • 所以如果我这样做:example.Instance.prop1 = 1;它实际上是将其放入示例对象中,但也会自动将其保存到会话中?
    【解决方案3】:
    using System.Web;
    using System.Web.SessionState;
    using System.Collections.Generic;
    
    public static class ExampleSession
    {
        private static HttpSessionState session { get { return HttpContext.Current.Session; } }
    
        public static string UserName
        {
            get { return session["username"] as string; }
            set { session["username"] = value; }
        }
    
        public static List<string> ProductsSelected
        {
            get
            {             
                if (session["products_selected"] == null)
                    session["products_selected"] = new List<string>();
    
                return (List<string>)session["products_selected"];        
            }
        }
    }
    

    你可以像这样使用它:

    public class main
    {
       protected void Page_Load(object sender, EventArgs e)
       {
          //stores value into session
          ExampleSession.UserName = "foo";
          ExampleSession.ProductsSelected.Add("bar"); 
          txtInput.Text = ExampleSession.UserName; //retrieves value from session
       }
    }
    

    【讨论】:

      【解决方案4】:
      public class example {
         public int prop1 { get; set; } 
      
         public static example Instance {
             var exampleObject = (example)(HttpContext.Current.Session["exampleClass"]
                                           ?? new example());
      
             HttpContext.Current.Session["exampleClass"] = exampleObject;
      
             return exampleObject; 
         } 
      
      }
      

      如果需要,您可以进一步优化它

      【讨论】:

        【解决方案5】:

        如果您正在寻找一种更加面向对象的会话方式,那么下面是一个很好的方式。

        用户会话类

        [Serializable()]
        public class UserSession
        {
        
            private CurrentRecord _CurrentRecord;
            public CurrentRecord CurrentRecord
            {
                get
                {
                    if ((_CurrentRecord == null))
                    {
                        _CurrentRecord = new CurrentRecord();
                    }
                    return _CurrentRecord;
                }
                set
                {
                    if ((_CurrentRecord == null))
                    {
                        _CurrentRecord = new CurrentRecord();
                    }
                    _CurrentRecord = value;
                }
            }
        }
        

        全局类

        public static class Globals
        {
            public static UserSession TheUserSession
            {
                get
                {
                    if ((HttpContext.Current.Session["UserSession"] == null))
                    {
                        HttpContext.Current.Session.Add("UserSession", new CurrentUserSession());
                        return (CurrentUserSession)HttpContext.Current.Session["UserSession"];
                    }
                    else
                    {
                        return (CurrentUserSession)HttpContext.Current.Session["UserSession"];
                    }
                }
                set { HttpContext.Current.Session["UserSession"] = value; }
            }
        }
        

        CurrentRecord 类

        [Serializable()]
        public class CurrentRecord
        {
            public int id { get; set; }
            public string name { get; set; }
        }
        

        在后面的代码中使用

            public void SetRecordId(int newId)
            {
                Globals.TheUserSession.CurrentRecord.id = newId;
            }
        

        【讨论】:

          猜你喜欢
          • 2017-01-17
          • 2012-06-18
          • 1970-01-01
          • 2013-08-04
          • 2012-12-29
          • 2017-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多