静态化过程的难度和动态页面“动态”因素成指数关系。如下是我最近应用而写的一个静态化处理抽象类BaseHandlerStaticizer:
BaseHandlerStaticizer
using System;
using System.IO;
using System.Text;
using System.Web;
/// <summary>
/// 提供抽象静态化服务.
/// Howard 20090420.
/// </summary>
public abstract class BaseHandlerStaticizer : IHttpHandler {
private const int ScriptTimeout = 60 * 5;// 5 分钟
private HttpContext _context;
protected HttpContext Context {
get { return _context; }
private set {
_context = value;
}
}
/// <summary>
/// 待处理的需要静态化的Url
/// </summary>
protected abstract string[] ProcessUrls {
get;
}
protected abstract bool PreserveForm {
get;
}
protected void Process() {
Context.Server.ScriptTimeout = ScriptTimeout;
StringBuilder builder;
foreach (string url in ProcessUrls) {
builder = new StringBuilder();
using (TextWriter tw = new StringWriter(builder)) {
Context.Server.Execute(url, tw, PreserveForm);
SaveStaticFile(url, builder.ToString());
}
}
}
/// <summary>
/// 保存静态文件
/// </summary>
/// <param name="contents"></param>
/// <param name="url"></param>
protected abstract void SaveStaticFile(string sourceUrl, string contents);
#region IHttpHandler 成员
bool IHttpHandler.IsReusable {
get { return false; }
}
void IHttpHandler.ProcessRequest(HttpContext context) {
try {
Context = context;
Process();
context.Response.ContentType = "text/plain";
context.Response.Write("Ok.");
}
catch (Exception E) {
context.Response.ContentType = "text/plain";
context.Response.Write(E.ToString());
}
}
#endregion
}
主要的静态化方法是 Process 函数, 如下:
Process
protected void Process() {
Context.Server.ScriptTimeout = ScriptTimeout;
StringBuilder builder;
foreach (string url in ProcessUrls) {
builder = new StringBuilder();
using (TextWriter tw = new StringWriter(builder)) {
Context.Server.Execute(url, tw, PreserveForm);
SaveStaticFile(url, builder.ToString());
}
}
}
将你的“动态”参数变为 querystring 形式,枚举各参数值调用 Context.Server.Execute 静态化你的动态页面,最后保存该静态页面为文件即可(扩展名可为 .htm 等)。注意保存为静态文件时的命名规则,比如 Default_1_1.htm, Default_1_2.htm 等。