本文目录
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(); } } } }
调用案例:
站点配置文件5. JsonHelper基于Newtonsoft.Json封装
JsonHelper6. 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还有很多,欢迎大家多多交流,谢谢!
来源:https://www.cnblogs.com/hmit/p/10768444.html