最近在研究ASP.NET MVC產生靜態頁,那麼今天也算個學習筆記吧!
實現原理及步驟:
1.通過ViewEngines.Engines.FindView尋找到對應的視圖,如果是部分視圖,則用:ViewEngines.Engines.FindPartialView;
2.設定內容物件裡的Model;
3.調用視圖的Render()方法,將渲染結果儲存到物理靜態檔案;
using System; using System.IO; using System.Text; using System.Web.Mvc; namespace Whir.Foundation.UI { /// <summary> /// 描述:靜態頁面產生協助類 /// </summary> public class StaticPageHelper { /// <summary> /// 根據View檢視窗產生靜態頁面 /// </summary> /// <param name="htmlPath">存放靜態頁面所在絕對路徑</param> /// <param name="context">ControllerContext</param> /// <param name="viewPath">視圖名稱</param> /// <param name="masterName">模板視圖名稱</param> /// <param name="model">參數實體模型</param> /// <param name="html">返回資訊</param> /// <param name="isPartial">是否分布視圖</param> /// <returns>產生成功返回true,失敗false</returns> public static AjaxResult GenerateStaticPage(string viewPath, string htmlPath, ControllerContext context, object model = null, bool isPartial = false, string masterName = "") { var ajaxResult = new AjaxResult(); try { //建立存放靜態頁面目錄 if (!Directory.Exists(Path.GetDirectoryName(htmlPath))) { Directory.CreateDirectory(Path.GetDirectoryName(htmlPath)); } //刪除已有的靜態頁面 if (File.Exists(htmlPath)) { File.Delete(htmlPath); } ViewEngineResult result = null; if (isPartial) { result = ViewEngines.Engines.FindPartialView(context, viewPath); } else { result = ViewEngines.Engines.FindView(context, viewPath, masterName); } if (model != null) { context.Controller.ViewData.Model = model; } /* * 設定臨時資料字典作為靜態化標識 * 可以在視圖上使用TempData["IsStatic"]來控制某些元素顯示。 */ if (!context.Controller.TempData.ContainsKey("IsStatic")) { context.Controller.TempData.Add("IsStatic", true); } if (result.View != null) { using (var sw = new StringWriter()) { var viewContext = new ViewContext(context, result.View, context.Controller.ViewData, context.Controller.TempData, sw); result.View.Render(viewContext, sw); string body = sw.ToString(); File.WriteAllText(htmlPath, body, Encoding.UTF8); ajaxResult.IsSucess = true; ajaxResult.Body = "存放路徑:" + htmlPath; } } else { ajaxResult.IsSucess = false; ajaxResult.Body = "產生靜態頁面失敗!未找到視圖!"; } } catch (IOException ex) { ajaxResult.IsSucess = false; ajaxResult.Body = ex.Message; } catch (Exception ex) { ajaxResult.IsSucess = false; ajaxResult.Body = ex.Message; } return ajaxResult; } } }
AjaxResult 是自己封裝的一個類,您也可以用自己封裝的類代替。
public class AjaxResult { public bool IsSucess { get; set; } public string Body { get; set; } }