Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created July 27, 2018 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ichiroku11/4c7d2f66c41c77cf80a2921c31a06d6a to your computer and use it in GitHub Desktop.
Save ichiroku11/4c7d2f66c41c77cf80a2921c31a06d6a to your computer and use it in GitHub Desktop.
ASP.NET Core MVC - セッションにオブジェクト
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace WebApp {
public static class SessionExtensions {
// セッションにオブジェクトを書き込む
public static void SetObject<TObject>(this ISession session, string key, TObject obj) {
var json = JsonConvert.SerializeObject(obj);
session.SetString(key, json);
}
// セッションからオブジェクトを読み込む
public static TObject GetObject<TObject>(this ISession session, string key) {
var json = session.GetString(key);
return string.IsNullOrEmpty(json)
? default(TObject)
: JsonConvert.DeserializeObject<TObject>(json);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment