在MVC下如何压缩输出的HTML代码,替换HTML代码中的空白,换行符等字符?
1.首先要了解MVC是如何输出HTML代码到客户端的,先了解下Controller这个类,里面有很多方法,我们需要的主要有两个:OnActionExecuting和OnResultExecuted
2.新建一个基类,继承自:System.Web.Mvc.Controller,代码如下:
- using System.IO;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.UI;
- namespace WebApplication2.Controllers
- {
- /// <summary>
- /// Base
- /// </summary>
- public class BaseController : Controller
- {
- #region Private
- /// <summary>
- /// HtmlTextWriter
- /// </summary>
- private HtmlTextWriter tw;
- /// <summary>
- /// StringWriter
- /// </summary>
- private StringWriter sw;
- /// <summary>
- /// StringBuilder
- /// </summary>
- private StringBuilder sb;
- /// <summary>
- /// HttpWriter
- /// </summary>
- private HttpWriter output;
- #endregion
- /// <summary>
- /// 压缩html代码
- /// </summary>
- /// <param name="text">html代码</param>
- /// <returns></returns>
- private static string Compress(string text)
- {
- Regex reg = new Regex(@"s*(</?[^s/>]+[^>]*>)s+(</?[^s/>]+[^>]*>)s*");
- text = reg.Replace(text, m => m.Groups[1].Value + m.Groups[2].Value);
- reg = new Regex(@"(?<=>)s| | (?=<)");
- text = reg.Replace(text, string.Empty);
- return text;
- }
- /// <summary>
- /// 在执行Action的时候,就把需要的Writer存起来
- /// </summary>
- /// <param name="filterContext">上下文</param>
- protected override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- sb = new StringBuilder();
- sw = new StringWriter(sb);
- tw = new HtmlTextWriter(sw);
- output = (HttpWriter)filterContext.RequestContext.HttpContext.Response.Output;
- filterContext.RequestContext.HttpContext.Response.Output = tw;
- base.OnActionExecuting(filterContext);
- }
- /// <summary>
- /// 在执行完成后,处理得到的HTML,并将他输出到前台
- /// </summary>
- /// <param name="filterContext"></param>
- protected override void OnResultExecuted(ResultExecutedContext filterContext)
- {
- string response = Compress(sb.ToString());
- output.Write(response);
- }
- }
- }
2.需要压缩的页面控制器,集成这个BaseController,就可以了,运行后的网页源代码如下图: