生成静态页
先定义一个StaticFileCacheModule
实现IHttpModule接口
定制BeginRequest事件
public class StaticFileCacheModule:IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
//判断是否需要处理
if (context.Request.AppRelativeCurrentExecutionFilePath.ToLower().EndsWith(".aspx"))
{
string fileUrl = "~/CacheFile/";
string fileName = GetFileName(context);
string filePath = context.Server.MapPath(fileUrl) + fileName;
if (File.Exists(filePath))
{
//如果静态缓存文件存在,直接返回缓存文件
context.RewritePath(fileUrl + fileName, false);
}
}
}
public static string GetFileName(HttpContext context)
{
//我们的缓存文件名由页面文件名加上查询字符串组成
return context.Request.AppRelativeCurrentExecutionFilePath.ToLower()
.Replace(".aspx", "").Replace("~/", "").Split('/')[context.Request.AppRelativeCurrentExecutionFilePath.ToLower()
.Replace(".aspx", "").Replace("~/", "").Split('/').Length-1]
+ context.Request.Url.Query.Replace("?", "__").Replace("&", "_") + ".html";
}
public void Dispose() {}
}
再定义一个类要生成静态页面的继承它就行了
public abstract class static_htm : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htmlw = new HtmlTextWriter(sw);
//调用Render方法,把页面内容输出到StringWriter中
base.Render(htmlw);
htmlw.Flush();
htmlw.Close();
//获得页面内容
string pageContent = sw.ToString();
string path = Server.MapPath("~/CacheFile/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string pageUrl = StaticFileCacheModule.GetFileName(HttpContext.Current);
if(!File.Exists(pageUrl))
{
//把页面内容保存到静态文件中
using (StreamWriter stringWriter = File.CreateText(path + pageUrl))
{
stringWriter.Write(pageContent); ;
}
}
//将页面内容输出到浏览器
Response.Write(pageContent);
}
}
当然不要忘在配置web.confing
<httpModules>
<add name ="StaticFileCache" type="StaticFileCacheModule"/>
</httpModules>
用模板生成静态页
模板文件: text.htm
<html>
<body>
<h4>[title]</h4>
<b>[tan]</b>
<h2>[conten]<h2>
</body>
</html>
代码:
private void GetWriter (string title,string tag,string content)
{
string path =HttpContext.Current.Server.MapPath("/StaticPage/");
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件
string temp = System.Web.HttpContext.Current.Server.MapPath("/StaticPage/text.htm");
StreamReader sr=null;
StreamWriter sw=null;
string str="";
try
{
sr = new StreamReader(temp, code);
str = sr.ReadToEnd(); // 读取文件
}
catch(Exception exp)
{
HttpContext.Current.Response.Write(exp.Message);
HttpContext.Current.Response.End();
sr.Close();
}
string htmlfilename=title+".html";
// 替换内容
// 这时,模板文件已经读入到名称为str的变量中了
str =str.Replace("[title] ",title); //模板页中的title
str =str.Replace("[tag] ",tag); //模板页中的tag
str =str.Replace("[content] ",content); //模板页中的content
// 写文件
try
{
sw = new StreamWriter(path + htmlfilename , false, code);
sw.Write(str);
sw.Flush();
}
catch(Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw.Close();
}
}
以上代码并非原著
再加一个
public void transHtml(string path, string outpath)
{
Page page = new Page();
StringWriter writer = new StringWriter();
page.Server.Execute(path, writer);
FileStream fs;
if (File.Exists(page.Server.MapPath("") + "\\" + outpath))
{
File.Delete(page.Server.MapPath("") + "\\" + outpath);
fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
}
else
{
fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
}
byte[] bt = Encoding.Default.GetBytes(writer.ToString());
fs.Write(bt, 0, bt.Length);
fs.Close();
}
transHtml("default3.aspx", "default3.html");
将为default3.aspx生成一个defult3.html的静态页面