1. 程式人生 > >ASP.NET 動態轉靜態頁面的兩種方法總結

ASP.NET 動態轉靜態頁面的兩種方法總結

1、建立MyConvert.cs類檔案 using System; //記得新增以下三引用 using System.Text; using System.Web; using System.IO; namespace TesConvert { /// /// MyConvert 的摘要說明。 /// public class MyConvert { public MyConvert() { // // TODO: 在此處新增建構函式邏輯 // } public bool WriteFile(string strText,string strContent,string strAuthor) { string path = HttpContext.Current.Server.MapPath("/TesConvert/news/");//定義html檔案存放路徑 Encoding code = Encoding.GetEncoding("gb2312");//定義文字編碼 // 讀取模板檔案 string temp = HttpContext.Current.Server.MapPath("/TesConvert/text.html"); StreamReader sr=null; StreamWriter sw=null; string str=""; try { sr = new StreamReader(temp, code); str = sr.ReadToEnd(); // 讀取檔案 } catch(Exception exp) { HttpContext.Current.Response.Write(exp.Message); HttpContext.Current.Response.End(); sr.Close(); } string htmlfilename=path + DateTime.Now.ToString("yyyyMMddHHmmss")+".html"; // 替換內容 // 這時,模板檔案已經讀入到名稱為str的變數中了 str = str.Replace("ShowArticle",strText); //模板頁中的ShowArticle str = str.Replace("title",strText); str = str.Replace("content",strContent); str = str.Replace("author",strAuthor); // 寫檔案 try { sw = new StreamWriter(htmlfilename,false,code); sw.Write(str); sw.Flush(); } catch(Exception ex) { HttpContext.Current.Response.Write(ex.Message); HttpContext.Current.Response.End(); } finally { sw.Close(); } return true; } } } 2、TestNews.aspx檔案: 新增三和TextBox分別為:tbx_Title、tbx_Content、tbx_Author和一個Button:btn_AddNews。 TestNews.aspx.cs檔案 private void btn_AddNews_Click(object sender, System.EventArgs e) { MyConvert Hover = new MyConvert(); if(Hover.WriteFile(this.txb_Title.Text.ToString(),Server.HtmlDecode(this.txb_Content.Value),this.txb_Author.Text.ToString())) { Response.Write("新增成功"); } else { Response.Write("生成HTML出錯!"); } } 3、新增模板text.html檔案 ShowArticle title
content
author 說明:一.news資料夾必須賦予asp.net使用者寫入的許可權。這是一個簡單的實現例子,實際專案必須先將資料儲存到資料庫下面,在datagird中 呼叫資料庫下面html檔案的URL地址。二.預設情況下,我們是不能向TextBox、TextArea中新增html語法的,必須修改config檔案,在 下面新增 ,但是這樣做的話,整個專案中都允許鍵入html標籤了,暫時還不知道其他的方。 缺點:這種方法是在ASP.net在頁面所有內容生成後、輸出內容前對頁面內容進行操作以前曾說過用HttpModule來在Response前更改,不夠靈活 ,每行修改response,比較費力。