asp.net WebPage WebMvc 压缩输出html

压缩 html 可以去除代码中无用的空格等,这样可提高网站的加载速度并节省带宽。

1.webpage项目可以重写Render方法,达到压缩输出的目的

    /// <summary>  
    /// PageBase  
    /// </summary>  
    public class PageBase : Page  
    {  
        /// <summary>  
        /// 重写Render方法,来压缩输出的内容  
        /// </summary>  
        /// <param name="writer"></param>  
        protected override void Render(HtmlTextWriter writer)  
        {  
            StringWriter html = new StringWriter();  
            HtmlTextWriter tw = new HtmlTextWriter(html);  
            base.Render(tw);  
            string outhtml = html.ToString();  
            //压缩  
            outhtml = Regex.Replace(outhtml, @"\s+(?=<)|\s+$|(?<=>)\s+", string.Empty);  
            outhtml = outhtml.Trim();  
            //输出到客户端  
            writer.Write(outhtml);  
        }  
    }  

2.MVC项目可以新建一个方法头属性,如下,然后再需要压缩的View方法头上增加 [Yasuo]

    public class YasuoAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;
            var response = filterContext.HttpContext.Response;
            #region GZip
            bool allowCompression = true;
            //bool.TryParse(ConfigurationManager.AppSettings["Compression"], out allowCompression); 
            if (allowCompression)
            {
                string acceptEncoding = request.Headers["Accept-Encoding"];
                if (string.IsNullOrEmpty(acceptEncoding)) return;
                acceptEncoding = acceptEncoding.ToUpperInvariant();
                if (acceptEncoding.Contains("GZIP"))
                {
                    response.AppendHeader("Content-encoding", "gzip");
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                }
                else if (acceptEncoding.Contains("DEFLATE"))
                {
                    response.AppendHeader("Content-encoding", "deflate");
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                }
            }
            #endregion
#if !DEBUG
            response.Filter = new HtmlYasuoFilter(response.Filter, s =>
            {
                s = Regex.Replace(s, @"\s+(?=<)|\s+$|(?<=>)\s+", "");
                //single-line doctype must be preserved
                var firstEndBracketPosition = s.IndexOf(">");
                if (firstEndBracketPosition >= 0)
                {
                    s = s.Remove(firstEndBracketPosition, 1);
                    s = s.Insert(firstEndBracketPosition, ">");
                }
                return s;
            });
#endif
        }
    }

使用方法:

[Yasuo] 
public ActionResult Index() 
{ 
    return View(); 
}

转载请说明出处:第六感博客 原文链接:

相关阅读:

C#使用RSA非对称加密字符串 附Helper帮助类

asp.net 内置委托 Action 和 Func 和 Predicate

vs生成成功但发布时报错 未能将文件...复制到... 未能找到文件...

FluentData 报错 Error:Could not map ...字段名