简体   繁体   中英

How to create a C# session object wrapper?

如何创建一个类库,我可以在其中获取和设置IIS Session对象,我使用var x = objectname("key")来获取值或objectname("key") = x来设置值?

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.

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.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM