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
