Asp.net Core Session 存储任意对象

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);
    }
}

依赖 Newtonsoft.Json

参考:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state

 

posted @ 2017-07-26 08:30  Bob1227  阅读(2181)  评论(0编辑  收藏  举报