How to create a wrapper for a C # session object?

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

+4
source share
3 answers

Usually I only have a static class that transfers my session data and makes it safe, for example:

 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 the item, you simply do the following:

 // Set MySessionHelper.CustomItem1 = "Hello"; // Get string test = MySessionHelper.CustomItem1; 

Is this what you were looking for?

EDIT:. In accordance with my comment on your question, you should not access the session directly from the pages of your application. The wrapper class will not only make the type of access safe, but it will also give you a central point for all changes. With a shell-based application, you can easily replace the session for the data store of your choice at any time without changing every page that uses the session.

Another thing that I like about using the wrapper class is that it documents all the data stored in the session. The next programmer that appears can see everything that is stored in the session by simply looking at the wrapper class, so you are less likely to store the same data several times or reprogram data that is already cached in the session.

+10
source

I think you could use a common dictionary like Dictionary<string, Object> or something similar to achieve this effect. You will need to write shell code to add an object when accessing an element that does not exist, for example, the default user property in your Wrapper.

+5
source

You can use something 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"; 
+2
source

Source: https://habr.com/ru/post/1302173/


All Articles