首页静态化和定时执行
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然后采用线程的方式进行生成。
<%@ 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了。
最后希望对大家有用。
分类: 互联网应用
作者: Leo_wl
出处: http://www.cnblogs.com/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息