發布時間:2021-03-25 16:37 作者:獨孤劍 閱讀:2183
1. 使用場景
適用于服務器功能不強的web站點,不希望頻繁通過讀取數據庫來展示內容,當有新的內容產生時,生成靜態頁面存放內容,數據庫中只保留如標題,類別等一些查詢關鍵字。
2. 使用靜態頁面的好處
(1)提高網站的訪問速度
(2)減輕服務器負擔
(3)利于搜索引擎抓取
3. ASP.NET生成靜態頁面的思路
(1)創建模板template.html文件,在里面定義一些特殊的字符串格式用于替換內容,如$htmlformat
(2)讀取模板內容到指定對象中
(3)將特殊的字符串格式替換為你想要的內容
(4)創建新的靜態頁面,并將替換完標簽的內容寫入到文件中即可
4.實現
定義html模板文件"template.html",注意標簽里內容
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <!--標題--> <div>$htmlformat[0]</div> <!--內容--> <div>$htmlformat[1]</div> </body> </html>
protected void Button1_Click(object sender, EventArgs e) { // 01.讀取html模板 string template = ""; try { using (StreamReader sr = new StreamReader(Server.MapPath("template.html"))) { template = sr.ReadToEnd(); } } catch (Exception ex) { Response.Write(ex.Message); Response.Write("<script>alert('讀取文件錯誤.')</script>"); } // 02.定義和html標記數目一致的數組并賦值 string[] format = new string[4]; format[0] = "這里是標題"; format[1] = "這里是內容"; // 03.替換html模板里的標簽為實際想要的值 for (int i = 0; i < 4; i++) { template = template.Replace("$htmlformat[" + i + "]", format[i]); } // 04.生成html文件 try { using (StreamWriter sw = new StreamWriter(Server.MapPath("output.html"), false, Encoding.UTF8)) { sw.WriteLine(template); } Response.Write("<script>alert('已生成html文件.')</script>"); } catch { Response.Write("生成html文件失敗."); } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞