[转载]asp.net 网站纯静态化设计及其实现

转载asp.net 网站纯静态化设计及其实现 - 饥饿定义我 - 博客园.

引言:为减轻服务器压力,较少伪静态对CPU的消耗,下面使用了纯静态的方式提供站点访问!

一、流程图如下

二、逐步分析

    A.捕获404,获取请求地址

    用户访问站点地址如下(例如:www.yahoo.com/news/1.html)

这时如果站点中存在如下文件即可快速的完成访问,为什么呢?因为是真实的,纯html文件呗!

不存在,那就是这套流程发挥效用的时候了!找不到文件,你肯定能得到404的错误

    这时在Global.asax文件中,写下如下代码:
[csharp]
protected void Application_Error(object sender, EventArgs e)
{

Exception error = Server.GetLastError();

HttpException httpException = error as HttpException;

if (httpException != null)
{
int httpCode = httpException.GetHttpCode();

if (httpCode == 404)
{

Server.ClearError();
string ruleType, htmlcache, cacheName;
string errorUrl = Request.RawUrl;//请求页面地址
}
}
}
[/csharp]

B.静态地址和动态地址的转化

到目前为止你得到了页面的真是请求地址,(例如:www.yahoo.com/news/1.html),这时你需要做一个转换,将真是的请求地址转换为动态(aspx)地址,那么转换的关系的配置文件,我配置在一个xml中使用url rewriter格式编写

如下:

1     <RewriterRule>
2       <LookFor>/news/(\d+).html</LookFor>
3       <SendTo>News.aspx?pageIndex=$0</SendTo>
4     </RewriterRule>

转化方法略

C.发送HTTP请求,向动态地址请求html内容,在Global.asax直接Response.Write(“返回的html”);
[csharp]
WebRequest wrt = null;
WebResponse wrse = null;

try
{
wrt = WebRequest.Create("真实地址");
wrse = wrt.GetResponse();
Stream strM = null;
StreamReader SR = null;

try
{
strM = wrse.GetResponseStream();
SR = new StreamReader(strM, code);

string strallstrm = SR.ReadToEnd();
return strallstrm;
}
catch (Exception ex)
{ }
}
[/csharp]
D.异步生成静态文件,供下次访问(异步请求的好处,用户不必等待,完成获取内容用户即可看到网页,生成静态页面由另一条线程完成)
[csharp]
public delegate bool MakeHtmlDelegate(string htmlContent, string path);//htmlContent html内容,path 文件存放目录及其文件名称
AsyncCallback callBack = new AsyncCallback(Procdss);
MakeHtmlDelegate deleg = new MakeHtmlDelegate(生成方法);
IAsyncResult async = deleg.BeginInvoke(htmlContent,path), callBack, deleg);

void Procdss(IAsyncResult async)
{
MakeHtmlDelegate deleg = async.AsyncState as MakeHtmlDelegate;
if (deleg != null)
{
bool isSuc = deleg.EndInvoke(async);
}
}
[/csharp]