Created
July 27, 2018 01:55
-
-
Save ichiroku11/4c7d2f66c41c77cf80a2921c31a06d6a to your computer and use it in GitHub Desktop.
ASP.NET Core MVC - セッションにオブジェクト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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