asp.net|靜態|頁面
當我們的網站訪問量很大的時候,用戶端的每一次POST都去大量調用資料庫伺服器是一件多麼可怕的事。系統效能會大打折扣,輕則速度很慢、資料庫鎖死,重則系統崩潰。本文將通過實現靜態HTML頁面解決這個問題。
1、建立Conn.cs類檔案
using System;
//記得添加以下三引用
using System.Text;
using System.Web;
using System.IO;
namespace myservers
{
/// <summary>
/// Conn 的摘要說明。
/// </summary>
public class Conn
{
public Conn()
{
//
// TODO: 在此處添加建構函式邏輯
//
}
public bool WriteFile(string strText,string strContent,string strAuthor)
{
string path = HttpContext.Current.Server.MapPath("/myservers/news/");//定義html檔案存放路徑
Encoding code = Encoding.GetEncoding("gb2312");//定義文字編碼
// 讀模數板檔案
string temp = HttpContext.Current.Server.MapPath("/myservers/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、AddNews.aspx檔案
添加三和TextBox分別為:tbx_Title、tbx_Content、tbx_Author和一個Button:btn_AddNews。
AddNews.aspx.cs檔案
private void btn_AddNews_Click(object sender, System.EventArgs e)
{
Conn Hover = new Conn();
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檔案
<head>ShowArticle</head>
<body>
title<br>
content<br>
author
</body>
說明:news檔案夾必須賦予asp.net使用者寫入的許可權。這是一個簡單的實現例子,實際項目必須先將資料儲存到資料庫下面,在datagird中調用資料庫下面html檔案的URL地址。
評論
# re: asp.net下實現靜態頁面(html) 2005-09-12 23:52 sunshine
注意:預設情況下,我們是不能向TextBox、TextArea中添加html文法的,必須修改config檔案,在<system.web>下面添加<pages validateRequest="false" />,但是這樣做的話,整個項目中都允許鍵入html標籤了,暫時還不知道其他的方法。
必須使用Server.HtmlDecode(this.Content.Value).ToString()對字元解碼!!!