在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
- {
-
-
-
- public class BaseController : Controller
- {
- #region Private
-
-
-
-
- private HtmlTextWriter tw;
-
-
-
- private StringWriter sw;
-
-
-
- private StringBuilder sb;
-
-
-
- private HttpWriter output;
-
- #endregion
-
-
-
-
-
-
- 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|\n|\t(?=<)");
- text = reg.Replace(text, string.Empty);
-
- return text;
- }
-
-
-
-
-
- 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);
- }
-
-
-
-
-
- protected override void OnResultExecuted(ResultExecutedContext filterContext)
- {
- string response = Compress(sb.ToString());
-
- output.Write(response);
- }
- }
- }

2.需要压缩的页面控制器,集成这个BaseController,就可以了,运行后的网页源代码如下图:

MVC下压缩输入的HTML内容
原文:http://www.cnblogs.com/webenh/p/6206215.html