Skip to content

Instantly share code, notes, and snippets.

@farukcan
Last active November 3, 2022 14:36
Show Gist options
  • Save farukcan/278438550ffff3bfb5ffca9887bab5bb to your computer and use it in GitHub Desktop.
Save farukcan/278438550ffff3bfb5ffca9887bab5bb to your computer and use it in GitHub Desktop.
DotNetCore Session Extension
using System.Text.Json;
using Microsoft.AspNetCore.Http;
// source : https://www.learmoreseekmore.com/2020/05/dotnet-core-session.html
// usage : InfoModel info = HttpContext.Session.Get<InfoModel>("info");
// usage : HttpContext.Session.Set<InfoModel>("info", info);
namespace SessionMvc.App.Utilities
{
public static class SessionExtension
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonSerializer.Serialize(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default : JsonSerializer.Deserialize<T>(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment