Asp.Net Core 2.0 项目实战(8)Core下缓存操作、序列化操作、JSON操作等Helper集合类

Asp.Net Core 2.0 项目实战(1) NCMVC开源下载了

Asp.Net Core 2.0 项目实战(2)NCMVC一个基于Net Core2.0搭建的角色权限管理开发框架

Asp.Net Core 2.0 项目实战(3)NCMVC角色权限管理前端UI预览及下载

Asp.Net Core 2.0 项目实战(4)ADO.NET操作数据库封装、 EF Core操作及实例

Asp.Net Core 2.0 项目实战(5)Memcached踩坑,基于EnyimMemcachedCore整理MemcachedHelper帮助类。

Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例

Asp.Net Core 2.0 项目实战(7)MD5加密、AES&DES对称加解密

Asp.Net Core 2.0 项目实战(8)Core下缓存操作、序列化操作、JSON操作等Helper集合类

Asp.Net Core 2.0 项目实战(9) 日志记录,基于Nlog或Microsoft.Extensions.Logging的实现及调用实例

Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录

Asp.Net Core 2.0 项目实战(11) 基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级

本文目录

1.  前沿
2.CacheHelper基于Microsoft.Extensions.Caching.Memory封装
3.XmlHelper快速操作xml文档
4.SerializationHelper文件序列化操作
5.JsonHelper基于Newtonsoft.Json封装
6.ByteConvertHelper byte转换操作类
7. 总结

1.  前沿

  Net Core2.0以前缓存操作、XML操作文档、处理JSON、序列化等都整理过相关帮助类,方便项目全局开发调用,但这些Helper在Net Core下面需要做调整才能使用,下面是我开发过程中整理的几个帮助类,可单独使用,仅供参考。

2.  CacheHelper基于Microsoft.Extensions.Caching.Memory封装

  在net core2.0下System.Web.Caching不在提供支持,取而代之的是Microsoft.Extensions.Caching.Memory,现在就基于新的类库做扩展封装。注意:netcore2.0文件依赖缓存好像没有扩展,修改文件信息后缓存自动更新功能暂未整合。

using System;
//using System.Web.Caching;//netcore2.0不再提供支持

using Microsoft.Extensions.Caching.Memory;
namespace NC.Common
{
    /// <summary>
    /// 为当前 HTTP 请求获取 Cache 对象。
    /// </summary>
    public class CacheHelper
    {
        static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
        /// <summary>
        /// 创建缓存项的文件
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="obj">object对象</param>
        public static void Set(string key, object value)
        {
            if (key != null)
            {
                cache.Set(key, value);
            }
        }
        /// <summary>
        /// 创建缓存项过期
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="obj">object对象</param>
        /// <param name="expires">过期时间(秒)</param>
        public static void Set(string key, object value, int expires)
        {
            if (key != null)
            {
                cache.Set(key, value, new MemoryCacheEntryOptions()
                    //设置缓存时间,如果被访问重置缓存时间。设置相对过期时间x秒
                    .SetSlidingExpiration(TimeSpan.FromSeconds(expires)));
            }
        }
        //dotnetcore2.0 文件依赖缓存好像没有,暂未找到。
        ///// <summary>
        ///// 创建缓存项的文件依赖
        ///// </summary>
        ///// <param name="key">缓存Key</param>
        ///// <param name="obj">object对象</param>
        ///// <param name="fileName">文件绝对路径</param>
        //public static void Set(string key, object obj, string fileName)
        //{
        //    //创建缓存依赖项
        //    CacheDependency dep = new CacheDependency(fileName);
        //    //创建缓存
        //    HttpContext.Current.Cache.Insert(key, obj, dep);
        //}

        /// <summary>
        /// 获取缓存对象
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns>object对象</returns>
        public static object Get(string key)
        {
            object val = null;
            if (key != null && cache.TryGetValue(key, out val))
            {

                return val;
            }
            else
            {
                return default(object);
            }
        }

        /// <summary>
        /// 获取缓存对象
        /// </summary>
        /// <typeparam name="T">T对象</typeparam>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            object obj = Get(key);
            return obj == null ? default(T) : (T)obj;
        }


        /// <summary>
        /// 移除缓存项的文件
        /// </summary>
        /// <param name="key">缓存Key</param>
        public static void Remove(string key)
        {
            cache.Remove(key);
        }

    }
}

3.  XmlHelper快速操作xml文档

  这里封装常见的对xml的操作和读取方法,追加节点,删除节点操作处理方法。配合序列化Hepler类处理。Core项目中实际使用过程中现仅用到SerializationHelper,里面序列化了xml并操作。由于xmlhelper做好了分享出来。

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace NC.Common
{
    public class XmlHelper
    {
        #region --增、删、改操作--

        /// <summary>
        /// 追加节点
        /// </summary>
        /// <param name="filePath">XML文档绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <param name="xmlNode">XmlNode节点</param>
        /// <returns></returns>
        public static bool AppendChild(string filePath, string xPath, XmlNode xmlNode)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode xn = doc.SelectSingleNode(xPath);
                XmlNode n = doc.ImportNode(xmlNode, true);
                xn.AppendChild(n);
                doc.Save(filePath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 从XML文档中读取节点追加到另一个XML文档中
        /// </summary>
        /// <param name="filePath">需要读取的XML文档绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <param name="toFilePath">被追加节点的XML文档绝对路径</param>
        /// <param name="toXPath">范例: @"Skill/First/SkillItem"</param>
        /// <returns></returns>
        public static bool AppendChild(string filePath, string xPath, string toFilePath, string toXPath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(toFilePath);
                XmlNode xn = doc.SelectSingleNode(toXPath);

                XmlNodeList xnList = ReadNodes(filePath, xPath);
                if (xnList != null)
                {
                    foreach (XmlElement xe in xnList)
                    {
                        XmlNode n = doc.ImportNode(xe, true);
                        xn.AppendChild(n);
                    }
                    doc.Save(toFilePath);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 修改节点的InnerText的值
        /// </summary>
        /// <param name="filePath">XML文件绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <param name="value">节点的值</param>
        /// <returns></returns>
        public static bool UpdateNodeInnerText(string filePath, string xPath, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode xn = doc.SelectSingleNode(xPath);
                XmlElement xe = (XmlElement)xn;
                xe.InnerText = value;
                doc.Save(filePath);
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 读取XML文档
        /// </summary>
        /// <param name="filePath">XML文件绝对路径</param>
        /// <returns></returns>
        public static XmlDocument LoadXmlDoc(string filePath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                return doc;
            }
            catch
            {
                return null;
            }
        }
        #endregion 增、删、改操作

        #region --读取XML的所有子节点--
        /// <summary>
        /// 读取XML的所有子节点
        /// </summary>
        /// <param name="filePath">XML文件绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <returns></returns>
        public static XmlNodeList ReadNodes(string filePath, string xPath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode xn = doc.SelectSingleNode(xPath);
                XmlNodeList xnList = xn.ChildNodes;  //得到该节点的子节点
                return xnList;
            }
            catch
            {
                return null;
            }
        }

        #endregion 扩展方法
    }
}

  以上用的是try catch这种处理,如果使用using可以参考一下链接:https://www.cnblogs.com/Chary/p/No0000DE.html

4.  SerializationHelper文件序列化操作

  对xml文件进行序列化并操作,可以参考。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace NC.Common
{
    public class SerializationHelper
    {
        public SerializationHelper() { }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="filename">文件路径</param>
        /// <returns></returns>
        public static object Load(Type type, string filename)
        {
            FileStream fs = null;
            try
            {
                // open the stream...
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(type);
                return serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }


        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="filename">文件路径</param>
        public static void Save(object obj, string filename)
        {
            FileStream fs = null;
            // serialize it...
            try
            {
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(fs, obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }

        }

    }
}

  调用案例:

#region--站点配置文件--
        /// <summary>
        ///  读取配置文件
        /// </summary>
        public NC.Model.siteconfig loadConfig()
        {
            NC.Model.siteconfig model = CacheHelper.Get<NC.Model.siteconfig>(JHKeys.CACHE_SYS_CONFIG);
            if (model == null)
            {
                //netcore2.0文件依赖缓存没有,暂时只能修改文件后手动清空一次缓存
                 //Utils.GetXmlMapPath(JHKeys.FILE_SYS_XML_CONFING);
//CacheHelper是NET Core下Microsoft.Extensions.Caching.Memory缓存帮助类
                CacheHelper.Set(JHKeys.CACHE_SYS_CONFIG, (NC.Model.siteconfig)SerializationHelper.Load(typeof(NC.Model.siteconfig), Utils.GetXmlMapPath(JHKeys.FILE_SYS_XML_CONFING)));
                model = CacheHelper.Get<NC.Model.siteconfig>(JHKeys.CACHE_SYS_CONFIG);
            }
            return model;
        }
        /// <summary>
        ///  保存配置文件
        /// </summary>
        public NC.Model.siteconfig saveConifg(NC.Model.siteconfig model)
        {
            return saveConifg(model, Utils.GetXmlMapPath(JHKeys.FILE_SYS_XML_CONFING));
        }
        private static object lockHelper = new object();
        /// <summary>
        /// 写入站点配置文件
        /// </summary>
        public NC.Model.siteconfig saveConifg(NC.Model.siteconfig model, string configFilePath)
        {
            // 清缓存
CacheHelper.Remove(JHKeys.CACHE_SYS_CONFIG);
            lock (lockHelper)
            {
                SerializationHelper.Save(model, configFilePath);
            }
            return model;
        }
#endregion
站点配置文件

5.  JsonHelper基于Newtonsoft.Json封装

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace NC.Common
{
    /// <summary>
    /// JSON帮助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary> 
        /// 对象转JSON 
        /// </summary> 
        /// <param name="obj">对象</param> 
        /// <returns>JSON格式的字符串</returns> 
        public static string ObjectToJSON(object obj)
        {
            try
            {
                byte[] b = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj));
                return Encoding.UTF8.GetString(b);
            }
            catch (Exception ex)
            {

                throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
            }
        }

        /// <summary> 
        /// 数据表转键值对集合
        /// 把DataTable转成 List集合, 存每一行 
        /// 集合中放的是键值对字典,存每一列 
        /// </summary> 
        /// <param name="dt">数据表</param> 
        /// <returns>哈希表数组</returns> 
        public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
        {
            List<Dictionary<string, object>> list
                 = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }

        /// <summary> 
        /// 数据集转键值对数组字典 
        /// </summary> 
        /// <param name="dataSet">数据集</param> 
        /// <returns>键值对数组字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
        {
            Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();

            foreach (DataTable dt in ds.Tables)
                result.Add(dt.TableName, DataTableToList(dt));

            return result;
        }

        /// <summary> 
        /// 数据表转JSON 
        /// </summary> 
        /// <param name="dataTable">数据表</param> 
        /// <returns>JSON字符串</returns> 
        public static string DataTableToJSON(DataTable dt)
        {
            return ObjectToJSON(DataTableToList(dt));
        }

        /// <summary> 
        /// JSON文本转对象,泛型方法 
        /// </summary> 
        /// <typeparam name="T">类型</typeparam> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>指定类型的对象</returns> 
        public static T JSONToObject<T>(string jsonText)
        {
            //JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonText);
                //return jss.Deserialize<T>(jsonText);
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
            }
        }

        /// <summary> 
        /// 将JSON文本转换为数据表数据 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据表字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
        }

        /// <summary> 
        /// 将JSON文本转换成数据行 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据行的字典</returns>
        public static Dictionary<string, object> DataRowFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, object>>(jsonText);
        }
    }
}
JsonHelper

6.  ByteConvertHelper byte转换操作类

    Byte转换操作类这里主要配合session存储使用,net core 2.0存储session 类型为object,先转成byte存储,读取再通过byte转object。

    例如Session存储值是字符串;设置session:HttpContext.Session.SetString("name","hello world!");  获取session:string str = HttpContext.Session.GetString("name"); 

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace NC.Common
{
    /// <summary>
    /// byte转换操作类,主要用于Session存储
    /// </summary>
    public class ByteConvertHelper
    {
        /// <summary>
        /// 将对象转换为byte数组
        /// </summary>
        /// <param name="obj">被转换对象</param>
        /// <returns>转换后byte数组</returns>
        public static byte[] Object2Bytes(object obj)
        {
            byte[] serializedResult = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj));
            return serializedResult;
        }

        /// <summary>
        /// 将byte数组转换成对象
        /// </summary>
        /// <param name="buff">被转换byte数组</param>
        /// <returns>转换完成后的对象</returns>
        public static object Bytes2Object(byte[] buff)
        {
            return JsonConvert.DeserializeObject<object>(Encoding.UTF8.GetString(buff));
        }

        /// <summary>
        /// 将byte数组转换成对象
        /// </summary>
        /// <param name="buff">被转换byte数组</param>
        /// <returns>转换完成后的对象</returns>
        public static T Bytes2Object<T>(byte[] buff)
        {
            return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(buff));
        }
    }
}

  调用实例参考《Asp.Net Core 2.0 项目实战(11) 基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级》中的<3.5 Session相关操作>。

7.  总结

  以上帮助类只是为了快速开发,文中有些帮助类是由webform项目升级改造的,适合自己项目的一些封装,仅供参考。需要做成帮助类全局调用的Helper还有很多,欢迎大家多多交流,谢谢!

 

posted @ 2018-04-12 12:51  郑州-在路上  阅读(3824)  评论(8编辑  收藏  举报