Home > Mobile >  Asp.Net core 6 session keys
Asp.Net core 6 session keys

Time:02-18

I had my project running on .NET framework 4.8 and then I migrated it to .NET 6. Whenever I needed to access specific properties from Session I used:

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

How can I achieve this in Asp.Net core 6? What I know that I need to add builder.Services.AddHttpContextAccessor(); in Program.cs and then inject to desired location. I tried but to no avail:

public static bool SIMInside
        {
            get
            {
                return _contextAccessor.HttpContext.Session.Get("SIMInside");
            }
            set
            {
                _contextAccessor.HttpContext.Session.Set("SIMInside", value);
            }
        }

In this case here Get returns byte[] array or Set requires byte[] array also

CodePudding user response:

ASP.NET Core has a different way to use session compare to classic ASP.NET Application.

Unfortunately you can no longer store complex objects in it. To store object it is converted into JSON and stored as a string. Later, it is retrieved as a string and deserialized to the original object.

In your case you can use SetInt32 and GetInt32 to store and retrieve 1 for true an 0 for false and then parse the value.

Convert.ToBoolean(session.GetInt32(“SIMInside”));

session.SetInt32(“SIMInside”, Convert.ToInt32(value));

Don’t forget to enable app.UseSession(); to be able to use session.

  • Related