The ASP.NET Session object has 3 methods to set the session value, which are Set, SetInt32 and SetString. The Set method accepts a byte array as an argument where the SetInt32 and SetString method are the extension methods of the Set method. These methods internally cast the int or string to a byte array. Similar to these, there are 3 methods used to retrieve the value from the session: Get, GetInt32 and GetString. There is no method available to in session, and this post shows how to complex objects in ASP.NET Core Session.

Store complex objects in ASP.NET Core Session

ASP.NET Core session objects store byte array to ensure that session values are serializable, as ASP.NET Core does not perform any operation such as serialization/deserialization on the values stored in the session. Unlike, the traditional ASP.NET session API allows you to set a session value by assigning any type to a session key. In ASP.NET Core, the only way to store other types of values/object in session is to implement the serialization to byte arrays.

Therefore, to store complex objects, we need to create an extension class to store and retrieve objects in session. Here, the object is converted into JSON and stored as a string. Later, it is retrieved as a string and deserialized to the original object. Like,

Now, you can store your complex objects as shown below:

var objComplex = new ComplexClass();
HttpContext.Session.SetObject("ComplexObject", objNew);

and get them as below:

var objComplex = HttpContext.Session.GetObject("ComplexObject");

Similarly, we can also add other custom extension methods to get and set the value in session for double and boolean. Like,

That’s it. ASP.NET Core has a different way to use session compare to classic ASP.NET Application. This post shows how to store complex objects in session with ASP.NET Core.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then

Buy Me A Coffee  - 1x1 - Store complex objects in ASP.NET Core Session

Source link


Please enter your comment!
Please enter your name here