本文主要講述了在asp.NET mvc中,頁面靜態化的方法。對于網站來說,生成純html靜態頁面除了有利于seo外,還可以減輕網站的負載能力和提高網站性能。
1.先付上封裝好生成靜態頁的原代碼:
public class Common{ #region 獲取模板頁的Html代碼 /// <summary> /// 獲取頁面的Html代碼 /// </summary> /// <param name="url">模板頁面路徑</param> /// <param name="encoding">頁面編碼</param> /// <returns></returns> public static string GetHtml(string url, System.Text.Encoding encoding) { byte[] buf = new WebClient().DownloadData(url); if (encoding != null) { return encoding.GetString(buf); } string html = System.Text.Encoding.UTF8.GetString(buf); encoding = GetEncoding(html); if (encoding == null || encoding == System.Text.Encoding.UTF8) { return html; } return encoding.GetString(buf); } /// <summary> /// 獲取頁面的編碼 /// </summary> /// <param name="html">Html源碼</param> /// <returns></returns> public static System.Text.Encoding GetEncoding(string html) { string pattern = @"(?i)/bcharset=(?<charset>[-a-zA-Z_0-9]+)"; string charset = Regex.Match(html, pattern).Groups["charset"].Value; try { return System.Text.Encoding.GetEncoding(charset); } catch (ArgumentException) { return null; } } #endregion #region 用于生成Html靜態頁 /// <summary> /// 創建靜態文件 /// </summary> /// <param name="result">Html代碼</param> /// <param name="createpath">生成路徑</param> /// <returns></returns> public static bool CreateFileHtmlByTemp(string result, string createpath) { if (!string.IsNullOrEmpty(result)) { if (string.IsNullOrEmpty(createpath)) { createpath = "/default.html"; } string filepath = createpath.Substring(createpath.LastIndexOf(@"/")); createpath = createpath.Substring(0, createpath.LastIndexOf(@"/")); if (!Directory.Exists(createpath)) { Directory.CreateDirectory(createpath); } createpath = createpath + filepath; try { FileStream fs2 = new FileStream(createpath, FileMode.Create); StreamWriter sw = new StreamWriter(fs2, new System.Text.UTF8Encoding(false));//去除UTF-8 BOM sw.Write(result); sw.Close(); fs2.Close(); fs2.Dispose(); return true; } catch (Exception ex) { throw ex; } } return false; } #endregion #region 調用靜態模板,并且傳遞數據模型實體類 創建Html靜態頁 /// <summary> /// 解析模板生成靜態頁 /// </summary> /// <param name="temppath">模板地址</param> /// <param name="path">靜態頁地址</param> /// <param name="t">數據模型</param> /// <returns></returns> public static bool CreateStaticPage<T>(string temppath, string path, T t) { try { //獲取模板Html string TemplateContent = GetHtml(temppath, System.Text.Encoding.UTF8); //初始化結果 string result = string.Empty; //解析模板生成靜態頁Html代碼 result = Razor.Parse(TemplateContent, t); //創建靜態文件 return CreateFileHtmlByTemp(result, path); } catch (Exception e) { throw e; } } #endregion}
新聞熱點
疑難解答
圖片精選