在ASP.NET中,怎么压缩输出的HTML内容,怎么替换HTML中的换行符,空白,TAB等符号呢?
1.新建一个基类,继承自System.Web.UI.Page,代码如下:
- using System.IO;
- using System.Text.RegularExpressions;
- using System.Web.UI;
- namespace Web.HttpModel.Demo
- {
- /// <summary>
- /// PageBase
- /// </summary>
- public class PageBase : Page
- {
- /// <summary>
- /// 重写Render方法,来压缩输出的内容
- /// </summary>
- /// <param name="writer"></param>
- protected override void Render(HtmlTextWriter writer)
- {
- StringWriter html = new StringWriter();
- HtmlTextWriter tw = new HtmlTextWriter(html);
- base.Render(tw);
- string outhtml = html.ToString();
- //压缩
- outhtml = Regex.Replace(outhtml, @"(?<=>)s| | (?=<)", string.Empty);
- outhtml = outhtml.Trim();
- //输出到客户端
- writer.Write(outhtml);
- }
- }
- }
2.新建Default.aspx页面,然后继承自上面的基类:PageBase,然后直接运行项目,然后查看源代码,如下图: