简体   繁体   中英

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

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.

https://youtu.be/e7UBAe0-KY8

I found this very useful video regarding Sessions in Net6, I think it'll help you and anyone else with this issue, I had myself

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