思路:增加一个Controller基类,用于压缩输出的HTML源代码,对输出html内容里的空格回车换行符等进行移除,需要压缩的Controller继承自这个基类即可。
如果js结尾不写分号的话,压缩后,页面脚本会受影响,按标准写的代码不会有影响,目前在我自己的项目中使用,尚未发现什么问题。
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace RC.Foundation.UI
{
public class BaseController : Controller
{
/// <summary>
/// 压缩html代码
/// </summary>
/// <param name="text">html代码</param>
/// <returns></returns>
private static string Compress(string text)
{
var reg = new Regex(@"\s*(</?[^\s/>]+[^>]*>)\s+(</?[^\s/>]+[^>]*>)\s*");
text = reg.Replace(text, m => m.Groups[1].Value + m.Groups[2].Value);
//移除html标签之间的空格
text = new Regex(@"(?<=>)[\s|\n|\t]*(?=<)").Replace(text, string.Empty);
//移除多余空格和换行符
text = new Regex(@"\n+\s+").Replace(text, string.Empty);
return text;
}
/// <summary>
/// 在执行Action的时候,就把需要的Writer存起来
/// </summary>
/// <param name="filterContext">上下文</param>
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
_builder = new StringBuilder();
_writer = new StringWriter(_builder);
_htmlWriter = new HtmlTextWriter(_writer);
_output = (HttpWriter) filterContext.RequestContext.HttpContext.Response.Output;
filterContext.RequestContext.HttpContext.Response.Output = _htmlWriter;
base.OnActionExecuting(filterContext);
}
/// <summary>
/// 在执行完成后,处理得到的HTML,并将他输出到前台
/// </summary>
/// <param name="filterContext"></param>
protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
var response = Compress(_builder.ToString());
_output.Write(response);
}
#region Private
/// <summary>
/// HtmlTextWriter
/// </summary>
private HtmlTextWriter _htmlWriter;
/// <summary>
/// StringWriter
/// </summary>
private StringWriter _writer;
/// <summary>
/// StringBuilder
/// </summary>
private StringBuilder _builder;
/// <summary>
/// HttpWriter
/// </summary>
private HttpWriter _output;
#endregion
}
}
输出结果类似这样: