ASP.NET静态页生成

时间:2023-08-19 17:41:08

由于业务需要,得把页面按照模板页生成静态页面,所以自己就琢磨了下,写些思路,以备日后需要的时候用。

静态页生成用到最多的就是匹配跟替换了,首先得读取模板页的html内容,然后进行你自己定义的标签匹配,比如说我要把我定义的标题标签换成读取数据库的标题内容,那么可以直接读取数据库的标题,然后直接进行替换,然后生成html文件就OK了。

代码:

/// <summary>
/// 解析模板的html中匹配的标签,进行替换(暂时只能用于没有分页的页面)
/// </summary>
/// <param name="html">HTML</param>
/// <returns>返回替换后的HTML</returns>
public static string ReturnHtml(string html)
{
string newhtml = html;
newhtml = newhtml.Replace("<#Title#>", "这个是标题替换");//替换标题
//newhtml = newhtml.Replace("<#Content#>", "这个是内容替换");//替换标题
newhtml = CreateList(newhtml);
return newhtml;
}
/// <summary>
/// 读取HTML文件
/// </summary>
/// <param name="temp">html文件的相对路径</param>
/// <returns>返回html</returns>
public static string ReadHtmlFile(string temp)
{
StreamReader sr = null;
string str = "";
try
{
sr = new StreamReader(HttpContext.Current.Server.MapPath(temp), code);
str = sr.ReadToEnd(); // 读取文件
}
catch (Exception exp)
{
HttpContext.Current.Response.Write(exp.Message);
HttpContext.Current.Response.End();
}
finally
{
sr.Dispose();
sr.Close(); }
return str;
}
/// <summary>
/// 生成html文件
/// </summary>
/// <param name="filmname">文件名(带相对路径路径,如:../a.html)</param>
/// <param name="html">html内容(整个)</param>
public static void writeHtml(string filmname, string html)
{
System.Text.Encoding code = System.Text.Encoding.GetEncoding("utf-8");
string htmlfilename = HttpContext.Current.Server.MapPath(filmname);
string str = html;
StreamWriter sw = null;
// 写文件
try
{
sw = new StreamWriter(htmlfilename, false, code);
sw.Write(str);
sw.Flush();
} catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
} finally
{
sw.Close();
} }

从代码可以看得出来,生成静态页面其实就是这么一个过程:读取模板页的源码->匹配替换自定义的标签为实际内容->最后再生成新的html文件,思路就这么走,以前没有动手过,觉得太复杂了,如今主动写的时候,发现也不算很复杂。

最后,如果说有些生成分页列表的,也就是把列表页面进行循环生成,有多少页就生成多少个静态页文件,如果有不懂的可以回复问,我懂的我尽量为大家解答,当然,不懂的我也无能为力了,毕竟我也是刚接触这功能,现在暂时弄得一个最简陋的样子,附图上来给大家笑话笑话:

ASP.NET静态页生成

最后是求助环节:这是小子的小站:www.weixh.net,求助SEO的大婶,请问我该怎么推广呢?