ASP.NET使用HttpHandler進行頁面靜態化(自動生成頁面)

這次的Demo是,一個根頁面,點擊鏈接創建子頁面,子頁面都是一個Template頁面進行替換的

在這裏插入圖片描述

一個根頁面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="List.aspx.cs" Inherits="Static.List" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h2>體育新聞</h2>
            
            <p><a href="News/Info_0.html">中國拳手</a></p>
            <p><a href="News/Info_1.html">納斯很少情緒激動</a></p>
        </div>
    </form>
</body>
</html>

新建一個類,做假數據用,代替數據庫的表

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Static
{
    public class News
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Time { get; set; }
        public string Content { get; set; }
    }
}

建一個類,使用List進行加載數據

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Static
{
    public class NewsManager
    {
       public  List<News> lists = new List<News>();
        public NewsManager()
        {
            lists.Add(new News()
            {
                Id=1,
                Time="1019年1月1日",
                Content="拳手的內容",
                Title="拳手的標題"
            });
            lists.Add(new News()
            {
                Id = 2,
                Time = "10年1月1日",
                Content = "情緒的內容",
                Title = "情緒的標題"
            });
        }
    }
}

新建一個News文件夾,建一個Tamplate的網頁,用來規範網頁
在這裏插入圖片描述

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <div>
        <p>{$Title}</p>

        <p>{$Time}</p>
        <p>{$Content}</p>
    </div>
</body>
</html>

建一個類進行操作,繼承IHttpHandlers

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Static
{
    public class FileStaticHandler : IHttpHandler
    {
        public bool IsReusable => true;

        public void ProcessRequest(HttpContext context)
        {
            string url = context.Request.RawUrl;
            //通過Url把id取到
            int last = url.LastIndexOf("_");
            int dot = url.LastIndexOf(".");
            int newId = int.Parse(url.Substring(last + 1, dot - last - 1));
            //生成路徑
            string userFilePath = context.Server.MapPath("~/News/Info_" + newId + ".html");
            //如果此路徑沒文件的話,就生成
            if (!File.Exists(userFilePath))
            {
                //我的加載在類裏面寫的
                NewsManager newsManager = new NewsManager();
                List<News> news = newsManager.lists;
                //獲取某個文件的路徑
                string tempPath = context.Server.MapPath("~/News/Template.html");
                //把此文件裏面的關鍵字替換掉
                //把這個文件序列化保存
                string tempHtml = ReadTemplate(tempPath);
                tempHtml = tempHtml.Replace("{$Title}", news[newId].Title);
                tempHtml = tempHtml.Replace("{$Time}", news[newId].Time);
                tempHtml = tempHtml.Replace("{$Content}", news[newId].Content);
                //輸出此文件
                WriteHtmlFile(userFilePath, tempHtml);
            }
            //輸出文件
            context.Response.WriteFile(userFilePath); 

        }

        private void WriteHtmlFile(string userFilePath, string tempHtml)
        {
            FileStream fs = new FileStream(userFilePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(tempHtml);
            sw.Close();
            fs.Close();

        }

        private string ReadTemplate(string tempPath)
        {
            if (!File.Exists(tempPath))
            {
                throw new Exception("新聞詳情頁面模板文件未找到!");
            }
            FileStream fs = new FileStream(tempPath, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            string tempHtml = sr.ReadToEnd();
            sr.Close();
            fs.Close();
            return tempHtml;

        }
    }
}

既然用了Handler,就要進行配置文件

在這裏插入圖片描述

<system.webServer>
    <handlers>
      <add name="test" path="News/*.html" verb="*" type="Static.FileStaticHandler" />
    </handlers>
  </system.webServer>

根頁面效果圖(記得顯示全部文件,否則會不顯示)
在這裏插入圖片描述

點擊了第一個鏈接,就生成了頁面
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章