Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net core 6 session keys

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

like image 924
Tobias Avatar asked Oct 26 '25 21:10

Tobias


1 Answers

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.

like image 64
NazaRN Avatar answered Oct 28 '25 10:10

NazaRN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!