using System.Linq; using Newtonsoft.Json; namespace Microsoft.AspNetCore.Http { /// /// Extensions for the object. /// public static class SessionExtensions { /// /// Sets a strong typed value. /// /// The value type. /// The current session. /// The key. /// The value. public static void SetValue(this ISession session, string key, T value) => session.SetString(key, JsonConvert.SerializeObject(value)); /// /// Gets a strong typed value. /// /// The value type. /// The current session. /// The key. /// The value. public static T GetValue(this ISession session, string key) => session.HasKey(key) ? JsonConvert.DeserializeObject(session.GetString(key)) : default; /// /// Gets a strong typed value or the fallback value. /// /// The value type. /// The current session. /// The key. /// A fallback value when the key is not present. /// The value. public static T GetValue(this ISession session, string key, T fallback) { if (session.HasKey(key)) return session.GetValue(key); return fallback; } /// /// Checks whether the session has the key available. /// /// The current session. /// The key. /// true when the key was found, otherwise false. public static bool HasKey(this ISession session, string key) => session.Keys.Contains(key); } }