Asp.Net Core 2.0 項目實戰(8)Core下緩存操做、序列化操做、JSON操做等Helper集合類

本文目錄

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還有不少,歡迎你們多多交流,謝謝!

相關文章
相關標籤/搜索