標籤:str board ide space empty 建立 font tle 上下
在MVC下如何壓縮輸出的HTML代碼,替換HTML代碼中的空白,分行符號等字元?
1.首先要瞭解MVC是如何輸出HTML代碼到用戶端的,先瞭解下Controller這個類,裡面有很多方法,我們需要的主要有兩個:OnActionExecuting和OnResultExecuted
2.建立一個基類,繼承自:System.Web.Mvc.Controller,代碼如下:
[csharp] view plain copy
- 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|\n|\t(?=<)");
- 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,就可以了,運行後的網頁原始碼如:
MVC下壓縮輸入的HTML內容