第一步:修改配置文件,在system.web节点下添加: type中写静态化处理类名,path中写要静态化的页面
<httpHandlers>
<add verb="*" path="BookDetail.aspx" type="HtmlHandler"/>
</httpHandlers>
第二步:编写静态化处理类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using BookShopModels;
/// <summary>
///页面静态化技术
/// </summary>
public class HtmlHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//1.获取用户访问的书籍编号
string bookid = context.Request.Params["bid"].ToString();
//2.获取要生成静态页面的路径
string url = context.Server.MapPath("BookDetails/"+bookid+".html");
//加锁,(如果有一人以上同时访问就不会报错)
context.Application.Lock();
//判断静态页是否存在
if (!File.Exists(url))
{
//3.获取模版路径
string TempUrl = context.Server.MapPath("BookDetails/template.html");
//4.获取模板内容
string content = "";
using (StreamReader reader = new StreamReader(TempUrl))
{
content = reader.ReadToEnd();//从开始读到尾部(读取模版内容)
}
//4.获取书籍对象
Books book = BookShopBLL.BookManager.GetBookById(Convert.ToInt32(bookid));
//5.替换模板内容为真实书籍内容
content = content.Replace("[WebRootPath]", context.Request.ApplicationPath)
.Replace("[Title]", book.Title.ToString())
.Replace("[BookId]", book.Id.ToString())
.Replace("[Author]", book.Author.ToString())
.Replace("[PublishName]", BookShopBLL.PublisherManager.GetPublisherById(book.PublisherId).Name)
.Replace("[PublishDate]", book.PublishDate.ToString())
.Replace("[ISBN]", book.ISBN.ToString())
.Replace("[UnitPrice]", book.UnitPrice.ToString())
.Replace("[ContentDescription]", book.ContentDescription.ToString())
.Replace("[TOC]", book.TOC.ToString());
//6.写入静态化内容页面
using (StreamWriter writer = new StreamWriter(url))
{
writer.Write(content);
}
}
//解锁
context.Application.UnLock();
//7.跳转到静态的实际路径(方法一)
context.Response.Redirect("~/BookDetails/"+bookid+".html");
//跳转到静态的实际路径(方法二)
//context.Server.Execute("~/BookDetails/" + bookid + ".html");
}
public bool IsReusable
{
get
{
return false;
}
}
}
|