liveBook · Manning

Session state extension method

As explained in Pro ASP.NET Core 7, Tenth Edition

A session state extension method is an extension method that serializes or deserializes application objects for storage through ASP.NET Core session state.

ASP.NET Core session state stores int, string, and byte[] values, not a Cart object directly. Extension methods on ISession bridge that gap by converting the object to and from JSON. section 8.2.5

Listing 8.23 The SessionExtensions.cs file in the SportsStore/Infrastructure folder
using System.Text.Json;

namespace SportsStore.Infrastructure {

   public static class SessionExtensions {
       
       public static void SetJson(this ISession session, 
               string key, object value) {
           session.SetString(key, JsonSerializer.Serialize(value));
       }
               
       public static T? GetJson<T>(this ISession session, string key) {
           var sessionData = session.GetString(key);
           return sessionData == null
               ? default(T) : JsonSerializer.Deserialize<T>(sessionData);
       }
   }
}

SessionExtensions.cs defines SetJson, which serializes a value through SetString, and GetJson<T>, which reads it through GetString and returns default(T) when the key is absent. section 8.2.5

A cart Razor Page can read HttpContext.Session.GetJson<Cart>("cart") and use a new Cart when no value exists. Storing the updated cart in session makes it available to later requests. section 8.2.5

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Implements both JSON conversion methods and shows cart retrieval; it does not detail session-state setup.
Examples
Uses SessionExtensions.cs and a cart Razor Page that reads the "cart" session key.
What it assumes
Assumes familiarity with C# extension methods and Razor Pages; explains why session values need conversion.
What you can do after
Build it from scratch to store application objects through ISession and retrieve them on later requests.
How it connects
Connects ISession, JSON serialization, Razor Pages, and shopping carts.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.