每次使用session来获取/设置对象属性

JMD*_*JMD 4 c# asp.net session

我试着搜索这个,但我甚至不确定如何用它来搜索.

我试图做的是有一个类,每次我访问它来改变它,我真的得到并设置会话的价值.

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

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

我希望这对我想要做的事情有意义.

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

Chu*_*way 6

这对于泛型来说很容易.

试一试.

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


Jam*_*son 5

看起来你很接近,但你没有任何东西可以在会话中实际存储对象。尝试这样的事情:

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

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


小智 5

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

您可以像这样使用它:

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