Fork me on GitHub
首页静态化和定时执行

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("首页生成成功!");
            }
        }<br><br>注意:如果大家出现乱码问题就改改编码System.Text.Encoding.UTF8为gb2312<br>3.定时生成静态首页<br>首先添加一个Global.asax然后采用线程的方式进行生成。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<%@ 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了。

最后希望对大家有用。

 

 

 
posted on 2012-05-12 21:52  HackerVirus  阅读(261)  评论(0编辑  收藏  举报