How to create a C# session object wrapper?

喜欢而已 提交于 2019-12-12 08:55:08

问题


How do I create a class library where I can get and set like the IIS Session object where I use var x = objectname("key") to get the value or objectname("key") = x to set the value?


回答1:


Normally I just have a static class that wraps my session data and makes it type safe like:

public static class MySessionHelper
{
    public static string CustomItem1
    {
        get { return HttpContext.Current.Session["CustomItem1"] as string; }
        set { HttpContext.Current.Session["CustomItem1"] = value; }
    }

    public static int CustomItem2
    {
        get { return (int)(HttpContext.Current.Session["CustomItem2"]); }
        set { HttpContext.Current.Session["CustomItem2"] = value; }
    }

    // etc...
}

Then when I need to get or set an item you would just do the following:

// Set
MySessionHelper.CustomItem1 = "Hello";

// Get
string test = MySessionHelper.CustomItem1;

Is this what you were looking for?

EDIT: As per my comment on your question, you shouldn't access the session directly from pages within your application. A wrapper class will make not only make the access type safe but will also give you a central point to make all changes. With your application using the wrapper, you can easily swap out Session for a datastore of your choice at any point without making changes to every single page that uses the session.

Another thing I like about using a wrapper class is that it documents all the data that is stored in the session. The next programmer that comes along can see everything that is stored in the session just by looking at the wrapper class so you have less chance of storing the same data multiple times or refetching data that is already cached in the session.




回答2:


I guess, you could use a generic dictionary like Dictionary<string, Object> or something similar to achieve this effect. You would have to write some wrapper code to add an Object when accessing a non-existend item by for example a custom default property in your Wrapper.




回答3:


You could use some thing like this

public class Session
{
    private static Dictionary<string, object> _instance = new Dictionary<string, object>();
    private Session()
    {            
    }

    public static Dictionary<string, object> Instance
    {
        get
        {
           if(_instance == null)
           {
               _instance = new Dictionary<string, object>();
           }
            return _instance;
        }
    }
}

And use it like this

Session.Instance["key"] = "Hello World";


来源:https://stackoverflow.com/questions/2322008/how-to-create-a-c-sharp-session-object-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!