首页 > 代码库 > MVC下压缩输入的HTML内容
MVC下压缩输入的HTML内容
在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内容
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。