页面静态化技术

第一步:修改配置文件,在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;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值