引言:為減輕服務器壓力,較少偽靜態對CPU的消耗,下面使用了純靜態的方式提供站點訪問!
一、流程圖如下
二、逐步分析
A.捕獲404,獲取請求地址
用戶訪問站點地址如下(例如:www.yahoo.com/news/1.html)
這時如果站點中存在如下文件即可快速的完成訪問,為什么呢?因為是真實的,純html文件唄!
不存在,那就是這套流程發揮效用的時候了!找不到文件,你肯定能得到404的錯誤
這時在Global.asax文件中,寫下如下代碼
1 protected void Application_Error(object sender, EventArgs e) 2 { 3 4 Exception error = Server.GetLastError(); 5 6 HttpException httpException = error as HttpException; 7 8 if (httpException != null) 9 { 10 int httpCode = httpException.GetHttpCode(); 11 12 if (httpCode == 404) 13 { 14 15 Server.ClearError(); 16 string ruleType, htmlcache, cacheName; 17 string errorUrl = Request.RawUrl;//請求頁面地址
18 } 19 } 20 }
B.靜態地址和動態地址的轉化
到目前為止你得到了頁面的真是請求地址,(例如:www.yahoo.com/news/1.html),這時你需要做一個轉換,將真是的請求地址轉換為動態(aspx)地址,那么轉換的關系的配置文件,我配置在一個xml中使用url rewriter格式編寫
如下:
1 <RewriterRule> 2 <LookFor>/news/(\d+).html</LookFor> 3 <SendTo>News.aspx?pageIndex=$0</SendTo> 4 </RewriterRule>
轉化方法略
C.發送HTTP請求,向動態地址請求html內容,在Global.asax直接Response.Write(“返回的html”);
1 WebRequest wrt = null; 2 WebResponse wrse = null; 3 4 try 5 { 6 wrt = WebRequest.Create("真實地址"); 7 wrse = wrt.GetResponse(); 8 Stream strM = null; 9 StreamReader SR = null; 10 11 try 12 { 13 strM = wrse.GetResponseStream(); 14 SR = new StreamReader(strM, code); 15 16 string strallstrm = SR.ReadToEnd(); 17 return strallstrm; 18 } 19 catch (Exception ex) 20 { } 21 }
D.異步生成靜態文件,供下次訪問(異步請求的好處,用戶不必等待,完成獲取內容用戶即可看到網頁,生成靜態頁面由另一條線程完成)
1 public delegate bool MakeHtmlDelegate(string htmlContent, string path);//htmlContent html內容,path 文件存放目錄及其文件名稱 2 AsyncCallback callBack = new AsyncCallback(Procdss); 3 MakeHtmlDelegate deleg = new MakeHtmlDelegate(生成方法); 4 IAsyncResult async = deleg.BeginInvoke(htmlContent,path), callBack, deleg); 5 6 void Procdss(IAsyncResult async) 7 { 8 MakeHtmlDelegate deleg = async.AsyncState as MakeHtmlDelegate; 9 if (deleg != null) 10 { 11 bool isSuc = deleg.EndInvoke(async); 12 } 13 }
生成方法略,使用I0即可
可以拍磚了。。。。。。。。。。。。