What is the preferred way to transfer session state to ASP.Net?

I have an ASP.Net project that uses session state, I would like to be a little more rigorous about how we access session state, I am not happy with all the lines floating around the code. I also need to know when a particular value is stored / updated in session state to track the last value of an object.

The string problem is easy to solve with constants, but that doesn't help tracking. Encapsulating them all in one class is attractive, but then I have to pass the session object to this class, and it seems a little dirty

I am thinking of using one of two options:

  • Extenders and setters to extend the session object
  • Extension method for a session object to return a class with getters and setters

The first gives me the syntax:

var thing = Session.GetThing();
Session.SetThing(thing);

The second gives:

var thing = Session.Wrapper().Thing;
Session.Wrapper().Thing = thing;

Both have their own appeal, although I tend to the second. In an ideal world, I would like to do this:

var thing = Session.Thing(); // easy to do
Session.Thing() = thing; // don't think it possible

What is the preferred way to work with this? Any of them, otherwise, or am I just doing it wrong?

+3
source share
2 answers

You do not need to pass the session to each class, you can:

public class State
{
    public string Something
    {
        get { return HttpContext.Current.Session["Something"] as string; }
        set { HttpContext.Current.Session["Something"] = value; }
    }
}

This, I think, is a typical approach. HttpContext has a property Currentthat is statically available.

+3
source

, , . , . - , , / , , / .

+1

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


All Articles