首頁靜態化和定時執行


1.首頁靜態我在前面已經提到過但是那種方式好像解決的不夠徹底,而且每次加載首頁會先生存index.aspx動態首頁,然后重寫該頁面,這樣帶給服務器的負荷還是不小的。因此我決定用以下方法進行首頁靜態化:

基本思路:首先要掌握這種靜態化首頁技術

              其次是要做間隔每10分鍾更新一次首頁靜態頁面

這樣做的好處是既能做到及時更新又不會給服務器很大的負荷。一箭雙雕多好呢。

2.下來我們就說說靜態化首頁的技術:

//獲取該頁面的url:Request.Url.AbsoluteUri
        string url = Request.Url.AbsoluteUri.Substring(0,Request.Url.AbsoluteUri.LastIndexOf("/"));
        url += "/index.aspx";

        string text;
        System.Net.WebRequest wReq = System.Net.WebRequest.Create(url);//請求頁面地址
        System.Net.WebResponse wResp = wReq.GetResponse();//響應該頁面

        System.IO.Stream respStream = wResp.GetResponseStream();
        System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.UTF8);
        text = reader.ReadToEnd();
        string path = System.Web.HttpContext.Current.Server.MapPath("index.html");
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.UTF8))
        {
            if (text.Trim() != "")
            {
                sw.Write(text);
                Response.Write("首頁生成成功!");
            }
        }

注意:如果大家出現亂碼問題就改改編碼System.Text.Encoding.UTF8為gb2312
3.定時生成靜態首頁
首先添加一個Global.asax然后采用線程的方式進行生成。
<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Threading" %>

<script RunAt="server">
    string LogPath;
    Thread thread;
    void html()
    {
        while (true)
        {
            string url = "http://localhost:3160/AspNetEye/index.aspx";

            string text;
            System.Net.WebRequest wReq = System.Net.WebRequest.Create(url);
            System.Net.WebResponse wResp = wReq.GetResponse();  //注意要先 using System.IO;
            System.IO.Stream respStream = wResp.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.UTF8);
            text = reader.ReadToEnd();
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(LogPath, false, System.Text.Encoding.UTF8))
            {
                if (text.Trim() != "")
                {
                    sw.Write(text);
                    sw.Close();
                }
            }
            Thread.CurrentThread.Join(1000 * 60*10);
        }
    }
    void Application_Start(object sender, EventArgs e)
    {
        LogPath = System.Web.HttpContext.Current.Server.MapPath("index.html");
        thread = new Thread(new ThreadStart(html));
        thread.Start();
    }

 這就ok了。

最后希望對大家有用。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM