Store complex objects in ASP.NET Core Session

The ASP.NET Core 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 store complex objects in session, and this post shows how to store 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

4 thoughts on “Store complex objects in ASP.NET Core Session

    1. Nikhil,

      Thanks for the feedback. No, the ASP.NET Core doesn’t have the extension method for setting the dates. I request you to read the document again as you might have missed one step just before the setting and getting date example provided on the link. The doc clearly says “If you add the following extension methods, you can set and get serializable objects to Session:”. So first, adding the extension method and then using it. Exactly what I mentioned on my post. Hope this clears the confusion.

Leave a Reply

Your email address will not be published. Required fields are marked *