Skip to content

Instantly share code, notes, and snippets.

@niisar
Last active June 20, 2020 10:07
Show Gist options
  • Save niisar/dfab8ec83a9b0b870c4d0377350e569f to your computer and use it in GitHub Desktop.
Save niisar/dfab8ec83a9b0b870c4d0377350e569f to your computer and use it in GitHub Desktop.
SessionExtensions in asp.net core 1.0
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T Get<T>(this ISession session,string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}
public class HomeController : Controller
{
const string SessionKeyName = "_Name";
const string SessionKeyYearsMember = "_YearsMember";
const string SessionKeyDate = "_Date";
public IActionResult Index()
{
// Requires using Microsoft.AspNetCore.Http;
HttpContext.Session.SetString(SessionKeyName, "Rick");
HttpContext.Session.SetInt32(SessionKeyYearsMember, 3);
return RedirectToAction("SessionNameYears");
}
public IActionResult SessionNameYears()
{
var name = HttpContext.Session.GetString(SessionKeyName);
var yearsMember = HttpContext.Session.GetInt32(SessionKeyYearsMember);
return Content($"Name: \"{name}\", Membership years: \"{yearsMember}\"");
}
public IActionResult SetDate()
{
// Requires you add the Set extension method mentioned in the article.
HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
return RedirectToAction("GetDate");
}
public IActionResult GetDate()
{
// Requires you add the Get extension method mentioned in the article.
var date = HttpContext.Session.Get<DateTime>(SessionKeyDate);
var sessionTime = date.TimeOfDay.ToString();
var currentTime = DateTime.Now.TimeOfDay.ToString();
return Content($"Current time: {currentTime} - "
+ $"session time: {sessionTime}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment