Skip to main content

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

16 thoughts to “Store complex objects in ASP.NET Core Session”

  1. Your code stores string not an object. It’s an object serialized as string, I can not retrive meta information relative to object’s type. For instance, different objects that inherit from the same base class, this approach will not me allow how to identify from which I am dealing it. For instance, a male / female object inherits from human class without any relevant property to distinguished.

  2. I am creating as show as above, but I am not able use session when I am on different controller where session is not created. Why is that happening? Is asp.net core session works like ‘view state’ where we can use values on same page

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

    what does now mean, what version of dotnet core?

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

    1. Inject HttpAccessor into the view.
      ex.
      @inject IHttpContextAccessor HttpContextAccessor
      @{
      object Permissions = HttpContextAccessor.HttpContext.Session.GetObject(“permissions”);
      }

  4. Running your code above, I get the following error:
    CS0411 The type arguments for method ‘SessionExtensions.GetObject(ISession, string)’ cannot be inferred from the usage. Try specifying the type arguments explicitly.

    Do I need to replace the T in your get method with the complex class type or is there something else I’m missing?

    1. Nevermind – got it to work by changing
      var objComplex = HttpContext.Session.GetObject(“ComplexObject”);
      to
      var objComplex = HttpContext.Session.GetObject(“ComplexObject”);
      Thanks, great post!

      1. Oops cut/paste error: I mean I changed
        var objComplex = HttpContext.Session.GetObject(“ComplexObject”);
        to
        var objComplex = HttpContext.Session.GetObject(“ComplexObject”)

        Thanks!

          1. I think the comment system might be removing the correction as it contains angle brackets so it thinks its a html tag

            the correct code is:

            var objComplex = HttpContext.Session.GetObject [angle bracket] type of object [angle bracket] (“ComplexObject”)

            as if you were creating a new generic List.

    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 *