现在的位置: 首页 > 综合 > 正文

动态页面静态化、、

2013年08月16日 ⁄ 综合 ⁄ 共 2233字 ⁄ 字号 评论关闭

1、拆中做法、 、 判断静态文件是否存在、不存在就新建一个(提前编辑好一个静态页模板

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <cebter>
    <fieldset>
        <legend>详细信息</legend>
        <table>
            <tr><td>书名:</td><td>[$title]</td></tr>
            <tr><td>作者:</td><td>[$author]</td></tr>
            <tr><td>出版社:</td><td>[$publisher]</td></tr>
        </table>
    </fieldset>
</cebter>
</body>
</html>
、最后根据占位符得到静态页面、 、 、 、)。

存在就直接转向静态文件、 、

2、配置web.config文件、

  <httpHandlers>
            <add verb="*" type="HtmlHandler,App_Code" path="*.html"/>
        </httpHandlers>

3、实现 IHttphandler 类、 、

  public void ProcessRequest(HttpContext context)
    {
        context.Request.ContentEncoding = Encoding.GetEncoding("utf-8");         // 编码格式 、 、
        context.Response.ContentEncoding = Encoding.GetEncoding("utf-8");   
        string url = context.Request.RawUrl;                                                               // 获得请求的原始 url 、、
        string temp = url.Remove(url.Length - 5);
        StringBuilder sb = new StringBuilder();
        foreach (char c in temp.Skip(temp.LastIndexOf('_')+1))
        {
            sb.Append(c.ToString());
        }                                                                                                                       //  取出 id  、、
        //context.Response.Write(sb);
        string urlPath = "~/htmls/book" + sb;
        lock(context.Application)                                                                           // 应用程序一次只能访问一个。 。
        {
            if (!File.Exists(context.Server.MapPath(urlPath)))
            {
                //如果不存在当前路径对应的文件则生成文件
                string strHtml = string.Empty;
                using (StreamReader sr = new StreamReader(context.Server.MapPath("~/htmls/Template.htm")))
                {
                    strHtml = sr.ReadToEnd();
                }
                strHtml = strHtml.Replace("[$title]", "C#高级编程");
                strHtml = strHtml.Replace("[$author]", "张小三");
                strHtml = strHtml.Replace("[$publisher]", "华尔街金融出版社");
                using(StreamWriter sw=new StreamWriter(context.Server.MapPath(urlPath))){
                    sw.Write(strHtml);
                }
            }

        }
        context.Server.Execute(urlPath);
    }

抱歉!评论已关闭.