C#.NET动态页面静态化生成

时间:2022-10-24 13:01:15

一,动态页面生成静态也的思路是怎样呢?

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$</title>
</head>
<body>
<div> <h1>标题:$sgin$</h1></div>
<div>
内容开始:$content$
</div>
<div>
作者:$author$
</div>
<div>时间:$time$</div>
<div>结束</div>
</body>
</html>

那代码中的$content$等标识是用来替换的标识

2》我们建一个MVC项目,在HomeControllor中的代码,如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml; namespace DynamicCreateStaticHtml.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
string htmlName = WriteFile(new HtmlModel()
{
Title = "生成静态页面",
Content = "动态自动生成静态页面并赋值的方法",
Author = "admin",
Time = DateTime.Now.ToString(),
Sgin = "生成静态页面"
});
if (!string.IsNullOrWhiteSpace(htmlName))
{
return Redirect("/StaticHtml/" + htmlName + ".html");
}
else
{
return Content("生成页面出错");
}
}
/// <summary>
/// 动态生成静态方法
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public string WriteFile(HtmlModel model)
{
//获取当前项目的文档物理路径,用于生产静态HTML页面存地址 string path = Server.MapPath("./StaticHtml/");
//gb2312简体中文编码
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件,在项目下的文件
string temp = Server.MapPath("/StaticHtml/HtmlTemp.html");
StreamReader sr = null;
StreamWriter sw = null;
string str = "";
string htmlfilename = Guid.NewGuid().ToString();
try
{
sr = new StreamReader(temp, code);
str = sr.ReadToEnd(); // 读取文件
//替换内容,模板文件已经读入到名称为str的变量中了
str = str.Replace("$title$", model.Title); //模板页中的title
str = str.Replace("$sgin$", model.Sgin); //模板页中的sgin
str = str.Replace("$content$", model.Content); //模板页中的content
str = str.Replace("$author$", model.Author);//模板页中的author
str = str.Replace("$time$", model.Time); //模板页中的time
// 写文件
sw = new StreamWriter(path + htmlfilename + ".html", false, code);
sw.Write(str);
sw.Flush();
}
catch (Exception ex)
{
}
finally
{
sw.Close();
sr.Close(); //必须关闭静态文件链接,要不然会报错
}
return htmlfilename;
}
/// <summary>
/// 替换实体
/// </summary>
public class HtmlModel
{
public string Title { get; set; }
public string Sgin { get; set; }
public string Content { get; set; }
public string Author { get; set; }
public string Time { get; set; }
}
}
}

3》由以上代码我们可以看到,我们将静态模板的标识替换成我们要显示的标识,然后返回这个页面,这也是动态页面静态话生成的核心思路,但是我们要注意模板的文件连接需要close,要不然可能会导致文件已占用的错误