ASP.NET實(shí)現(xiàn)靜態(tài)頁(yè)面方法淺析
ASP.NET實(shí)現(xiàn)靜態(tài)頁(yè)面的方法是什么呢?首先讓我們看看ASP.NET的源碼實(shí)例:
- ﹤!--Main.Aspx--﹥
 - ﹤%@ page language="C#" %﹥
 - ﹤%@ import namespace=System.IO %﹥
 - ﹤script runat="server"﹥
 - protected override void OnInit (EventArgs e)
 - {
 - int id;
 - try
 - {
 - id = int.Parse (Request.QueryString["id"]);
 - }
 - catch
 - {
 - throw (new Exception ("頁(yè)面沒(méi)有指定id"));
 - }
 - string filename=Server.MapPath("statichtml_"+id+".html");
 - //嘗試讀取已有文件
 - Stream s = GetFileStream (filename);
 - if (s != null)//如果文件存在并且讀取成功
 - {
 - using (s)
 - {
 - Stream2Stream (s, Response.OutputStream);
 - Response.End ();
 - }
 - }
 - //調(diào)用Main_Execute,并且獲取其輸出
 - StringWriter sw = new StringWriter ();
 - Server.Execute ("Main_Execute.aspx", sw);
 - string content = sw.ToString ();
 - //輸出到客戶端
 - Response.Write(content);
 - Response.Flush();
 - //寫進(jìn)文件
 - try
 - {
 - using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.Write))
 - {
 - using (StreamWriter streamwriter = new StreamWriter (fs, Response.ContentEncoding))
 - {
 - streamwriter.Write (content);
 - }
 - }
 - }
 - finally
 - {
 - //Response.End ();
 - }
 - }
 - static public void Stream2Stream (Stream src, Stream dst)
 - {
 - byte[] buf = new byte[4096];
 - while (true)
 - {
 - int c = src.Read (buf, 0, buf.Length);
 - if(c==0)
 - return;
 - dst.Write (buf, 0, c);
 - }
 - }
 - public Stream GetFileStream(string filename)
 - {
 - try
 - {
 - DateTime dt = File.GetLastWriteTime (filename);
 - TimeSpan ts=dt - DateTime.Now;
 - if(ts.TotalHours﹥1)
 - return null; //1小時(shí)后過(guò)期
 - return new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);
 - }
 - catch
 - {
 - return null;
 - }
 - }
 - ﹤/script﹥
 - ﹤!--Main_Execute.aspx--﹥
 - ﹤%@ page language="C#" %﹥
 - ﹤html﹥
 - ﹤head runat="server"﹥
 - ﹤title﹥Untitled Page﹤/title﹥
 - ﹤/head﹥
 - ﹤body﹥
 - ID:
 - ﹤%=Request.QueryString["id"]%﹥
 - ﹤/body﹥
 - ﹤/html﹥
 
其中ASP.NET實(shí)現(xiàn)靜態(tài)頁(yè)面的原理是這樣的。
Main_Execute.aspx是生成HTML的頁(yè)面。
現(xiàn)在用Main.aspx來(lái)對(duì)它進(jìn)行緩存.
ASP.NET實(shí)現(xiàn)靜態(tài)頁(yè)面過(guò)程如下:
首先根據(jù)頁(yè)面參數(shù)算出文件名。(這個(gè)例子只根據(jù)Request.QueryString["id"]來(lái)算)
嘗試讀取緩存的文件.如果成功,那么Response.End();
如果不成功:
使用Server.Execute來(lái)調(diào)用Main_Execute.aspx,并且獲取它的結(jié)果內(nèi)容。
得到內(nèi)容后,立刻輸出到客戶端。
***把內(nèi)容寫進(jìn)文件里,提供給下一次做為緩存度取。
ASP.NET實(shí)現(xiàn)靜態(tài)頁(yè)面的方法就向你介紹到這里,那么關(guān)于ASP.NET實(shí)現(xiàn)靜態(tài)頁(yè)面你是不是多了份了解了呢?
【編輯推薦】















 
 
 
 
 
 
 