zoukankan      html  css  js  c++  java
  • Asp.net5 Session Set扩展

     关于Asp.net 5 如何使用Session大家可以参考http://www.mikesdotnetting.com/article/270/sessions-in-asp-net-5 和http://www.cnblogs.com/TomXu/p/4496445.html。在实际项目用Session的类型最多的是int,String,bool 以及我们自定义的类型。 很多时候这些自定义类型是没有Serializable特性的。微软默认设置是采用字节,后来为了便于使用扩展了int和string类型。这里我的思路很简单用Newtonsoft.Json来序列化和反序列化来保存自定义类型

    using Microsoft.AspNet.Http;
        using Microsoft.AspNet.Http.Features;
        using Newtonsoft.Json;
        public static class SessionExtensions
            {
            public static bool? GetBoolean(this ISession session, string key)
            {
                var data = session.Get(key);
                if (data == null)
                {
                    return null;
                }
                return BitConverter.ToBoolean(data, 0);
            }
    
            public static void SetBoolean(this ISession session, string key, bool value)
            {
                session.Set(key, BitConverter.GetBytes(value));
            }
    
            public static T Get<T>(this ISession session, string key) where T :class,new()
            {
                var str = session.GetString(key);
                if (string.IsNullOrEmpty(str))
                {
                    return null;
                }
                return JsonConvert.DeserializeObject<T>(str);
            }
    
            public static void Set<T>(this ISession session, string key, T value) where T:class,new()
            {
                var str = JsonConvert.SerializeObject(value);
                session.SetString(key, str);
            }
        }

    这样在call session Api的时候就比较简单了, 如下:

    HttpContext.Session.Set<MyOptions>("test", Options);
    var b = HttpContext.Session.Get<MyOptions>("test");

  • 相关阅读:
    函数
    特殊集合
    集合
    数组复习
    数组
    IPython--转
    python 单例模式总结
    拼多多笔试题
    python 创建实例--待完善
    转--算法时间复杂度
  • 原文地址:https://www.cnblogs.com/majiang/p/5172262.html
Copyright © 2011-2022 走看看