產生單個的靜態頁面不是痛點,難的是各個靜態頁面間的關聯和連結如何保持完整;
特別是在頁面頻繁更新、修改、或刪除的情況下;
像阿里巴巴的頁面也全部是html的,估計用的是地址映射的功能
可以看看這個頁面,分析一下他的“競價倒計時”功能
在Asp中實現的產生靜態頁用到的FileSystemObject對象!
在.Net中涉及此類操作的是System.IO
以下是程式碼 注:此代碼非原創!參考別人代碼
//產生HTML頁
| 代碼如下 |
複製代碼 |
public static bool WriteFile(string strText,string strContent,string strAuthor) { string path = HttpContext.Current.Server.MapPath("/news/"); Encoding code = Encoding.GetEncoding("gb2312"); // 讀模數板檔案 string temp = HttpContext.Current.Server.MapPath("/news/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=DateTime.Now.ToString("yyyyMMddHHmmss")+".html"; // 替換內容 // 這時,模板檔案已經讀入到名稱為str的變數中了 str =str.Replace("ShowArticle",strText); //模板頁中的ShowArticle str = str.Replace("biaoti",strText); str = str.Replace("content",strContent); str = str.Replace("author",strAuthor); // 寫檔案 try { sw = new StreamWriter(path + 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; |
此函數放在Conn.CS基類中了
在添加新聞的代碼中引用 註:工程名為Hover
代碼如下:
| 代碼如下 |
複製代碼 |
if(Hover.Conn.WriteFilethis.Title.Text.ToString),this.Content.Text.ToString),this.Author.Text.ToString))) { Response.Write("添加成功"); } else { Response.Write("產生HTML出錯!"); } |
模板頁Text.html代碼
代碼如下:
| 代碼如下 |
複製代碼 |
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > < HTML> < HEAD> < title>ShowArticle< /title> < body> biaoti < br> content< br> author < /body> < /HTML> biaoti < br> content< br> author < /body> < /HTML> |
提示添加成功後會出以目前時間為檔案名稱的html檔案!上面只是把傳遞過來的幾個參數直接寫入了HTML檔案中,在實際應用中需要先添加資料庫,然後再寫入HTML檔案