生成缓存的html页面,页面生成--缓存法

a4c26d1e5885305701be709a3d33442f.png

页面生成--缓存法

(2007-04-06 11:37:03)

protected override void OnInit (EventArgs e)

{

int id;

try

{

id = int.Parse (Request.QueryString["id"]);

}

catch

{

throw (new Exception ("页面没有指定id"));

}

string filename=Server.MapPath("statichtml_"+id+".html");

//尝试读取已有文件

Stream s = GetFileStream (filename);

if (s != null)//如果文件存在并且读取成功

{

using (s)

{

Stream2Stream (s, Response.OutputStream);

Response.End ();

}

}

//调用Main_Execute,并且获取其输出

StringWriter sw = new StringWriter ();

Server.Execute ("Main_Execute.aspx", sw);

string content = sw.ToString ();

//输出到客户端

Response.Write(content);

Response.Flush();

//写进文件

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小时后过期

return new FileStream (filename, FileMode.Open,

FileAccess.Read, FileShare.Read);

}

catch

{

return null;

}

}

Untitled Page

ID:

其中原理是这样的.

Main_Execute.aspx是生成HTML的页面.

现在用Main.aspx来对它进行缓存.

过程如下:

首先根据页面参数算出文件名.(这个例子只根据Request.QueryString["id"]来算)

尝试读取缓存的文件.如果成功,那么Response.End();

如果不成功:

使用Server.Execute来调用Main_Execute.aspx,并且获取它的结果内容.

得到内容后,立刻输出到客户端.

最后把内容写进文件里,提供给下一次做为缓存度取.

分享:

a4c26d1e5885305701be709a3d33442f.png喜欢

0

a4c26d1e5885305701be709a3d33442f.png赠金笔

加载中,请稍候......

评论加载中,请稍候...

发评论

登录名: 密码: 找回密码 注册记住登录状态

昵   称:

评论并转载此博文

a4c26d1e5885305701be709a3d33442f.png

发评论

以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值