当我们压缩我的Response后再传到Client端时,可以明显节省宽带. 提升Site的性能. 现在的浏览器大部分都支持Gzip,Deflate压缩. 同时我们还可以删除一些空白
段,空行,注释等以使得HTML文档的尺寸变得更小. 让我们先来实现压缩与删除空白类, 继承自Stream类:

   1:      /// <summary>
   2:      /// CompressWhitespaceFilter
   3:      /// </summary>
   4:      public class CompressWhitespaceFilter : Stream
   5:      {
   6:          private GZipStream _contentGZipStream;
   7:          private DeflateStream _content_DeflateStream;
   8:          private Stream _contentStream;
   9:          private CompressOptions _compressOptions;
  10:   
  11:   
  12:          /// <summary>
  13:          /// Initializes a new instance of the <see cref="CompressWhitespaceFilter"/> class.
  14:          /// </summary>
  15:          /// <param name="contentStream">The content stream.</param>
  16:          /// <param name="compressOptions">The compress options.</param>
  17:          public CompressWhitespaceFilter(Stream contentStream, CompressOptions compressOptions)
  18:          {
  19:              if (compressOptions == CompressOptions.GZip)
  20:              {
  21:                  this._contentGZipStream = new GZipStream(contentStream, CompressionMode.Compress);
  22:                  this._contentStream = this._contentGZipStream;
  23:              }
  24:              else if (compressOptions == CompressOptions.Deflate)
  25:              {
  26:                  this._content_DeflateStream = new DeflateStream(contentStream,CompressionMode.Compress);
  27:                  this._contentStream = this._content_DeflateStream;
  28:              }
  29:              else
  30:              {
  31:                  this._contentStream = contentStream;
  32:              }
  33:              this._compressOptions = compressOptions;
  34:          }
  35:   
  36:          public override bool CanRead
  37:          {
  38:              get { return this._contentStream.CanRead; }
  39:          }
  40:   
  41:          public override bool CanSeek
  42:          {
  43:              get { return this._contentStream.CanSeek; }
  44:          }
  45:   
  46:          public override bool CanWrite
  47:          {
  48:              get { return this._contentStream.CanWrite; }
  49:          }
  50:   
  51:          public override void Flush()
  52:          {
  53:              this._contentStream.Flush();
  54:          }
  55:   
  56:          public override long Length
  57:          {
  58:              get { return this._contentStream.Length; }
  59:          }
  60:   
  61:          public override long Position
  62:          {
  63:              get
  64:              {
  65:                  return this._contentStream.Position;
  66:              }
  67:              set
  68:              {
  69:                  this._contentStream.Position = value;
  70:              }
  71:          }
  72:   
  73:          public override int Read(byte[] buffer, int offset, int count)
  74:          {
  75:              return this._contentStream.Read(buffer, offset, count);
  76:          }
  77:   
  78:          public override long Seek(long offset, SeekOrigin origin)
  79:          {
  80:              return this._contentStream.Seek(offset, origin);
  81:          }
  82:   
  83:          public override void SetLength(long value)
  84:          {
  85:              this._contentStream.SetLength(value);
  86:          }
  87:   
  88:          public override void Write(byte[] buffer, int offset, int count)
  89:          {
  90:              byte[] data = new byte[count + 1];
  91:              Buffer.BlockCopy(buffer, offset, data, 0, count);
  92:   
  93:              string strtext = System.Text.Encoding.UTF8.GetString(buffer);
  94:              strtext = Regex.Replace(strtext, "^\\s*", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
  95:              strtext = Regex.Replace(strtext, "\\r\\n", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
  96:              strtext = Regex.Replace(strtext, "<!--*.*?-->", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
  97:   
  98:              byte[] outdata = System.Text.Encoding.UTF8.GetBytes(strtext);
  99:              this._contentStream.Write(outdata, 0, outdata.GetLength(0));
 100:          }
 101:      }
 102:   
 103:      /// <summary>
 104:      /// CompressOptions
 105:      /// </summary>
 106:      /// <seealso cref="http://en.wikipedia.org/wiki/Zcat#gunzip_and_zcat"/>
 107:      /// <seealso cref="http://en.wikipedia.org/wiki/DEFLATE"/>
 108:      public enum CompressOptions
 109:      {
 110:          GZip,
 111:          Deflate,
 112:          None
 113:      }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

上面的代码使用正则表达式替换字符串,你可以修改那些正则表达式来满足你的需求. 我们同时使用了GZipStreamDeflateStream实现了压缩. 好的,接下来与
HttpModule结合:

   1:      /// <summary>
   2:      /// CompressWhitespaceModule
   3:      /// </summary>
   4:      public class CompressWhitespaceModule : IHttpModule
   5:      {
   6:          #region IHttpModule Members
   7:   
   8:          /// <summary>
   9:          /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
  10:          /// </summary>
  11:          public void Dispose()
  12:          {
  13:              // Nothing to dispose; 
  14:          }
  15:   
  16:          /// <summary>
  17:          /// Initializes a module and prepares it to handle requests.
  18:          /// </summary>
  19:          /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
  20:          public void Init(HttpApplication context)
  21:          {
  22:              context.BeginRequest += new EventHandler(context_BeginRequest);
  23:          }
  24:   
  25:          /// <summary>
  26:          /// Handles the BeginRequest event of the context control.
  27:          /// </summary>
  28:          /// <param name="sender">The source of the event.</param>
  29:          /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  30:          void context_BeginRequest(object sender, EventArgs e)
  31:          {
  32:              HttpApplication app = sender as HttpApplication;
  33:              if (app.Request.RawUrl.Contains(".aspx"))
  34:              {
  35:                  HttpContext context = app.Context;
  36:                  HttpRequest request = context.Request;
  37:                  string acceptEncoding = request.Headers["Accept-Encoding"];
  38:                  HttpResponse response = context.Response;
  39:                  if (!string.IsNullOrEmpty(acceptEncoding))
  40:                  {
  41:                      acceptEncoding = acceptEncoding.ToUpperInvariant();
  42:                      if (acceptEncoding.Contains("GZIP"))
  43:                      {
  44:                          response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.GZip);
  45:                          response.AppendHeader("Content-encoding", "gzip");
  46:                      }
  47:                      else if (acceptEncoding.Contains("DEFLATE"))
  48:                      {
  49:                          response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.Deflate);
  50:                          response.AppendHeader("Content-encoding", "deflate");
  51:                      }
  52:                  }
  53:                  response.Cache.VaryByHeaders["Accept-Encoding"] = true;
  54:              }
  55:          }
  56:   
  57:          #endregion
  58:      }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

HttpApplication.BeginRequest 事件是 在 ASP.NET 响应请求时作为 HTTP 执行管线链中的第一个事件发生。

在WEB.CONFIG中你还需要配置:

   1:  <httpModules>
   2:    <add name="CompressWhitespaceModule"  type="MyWeb.CompressWhitespaceModule" />
   3:  </httpModules>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

我们来看一下效果,下面没有使用时, 4.8KB

接着看,处理过后的效果,Cotent-Encoding: gzip,  filezie: 1.6KB

很简单,你可以按需求来增加更多的功能. 希望对您开发有帮助.

ASP.NET使用HttpModule压缩并删除空白Html请求的更多相关文章

  1. python学习:删除空白

    删除空白   删除尾部空白 确保字符串尾部没有空白,使用rstrip(); 删除字符串开头的空白,使用lstrip(); 同时删除字符串两端的空白,使用strip() 代码: >>> ...

  2. iOS 11开发教程(十六)iOS11应用视图之删除空白视图

    iOS 11开发教程(十六)iOS11应用视图之删除空白视图 当开发者不再需要主视图的某一视图时,可以将该视图删除.实现此功能需要使用到removeFromSuperview()方法,其语法形式如下: ...

  3. ASP.NET-自定义HttpModule与HttpHandler介绍

    ASP.NET对请求处理的过程:当请求一个*.aspx文件的时候,这个请求会被inetinfo.exe进程截获,它判断文件的后缀(aspx)之后,将这个请求转交给 ASPNET_ISAPI.dll,A ...

  4. tr---对来自标准输入的字符进行替换、压缩和删除。

    tr命令可以对来自标准输入的字符进行替换.压缩和删除.它可以将一组字符变成另一组字符,经常用来编写优美的单行命令,作用很强大. 语法 tr(选项)(参数) 选项 -c或——complerment:取代 ...

  5. winform程序,备份数据库+并压缩+并删除以前的备份

    说明:为了定时备份服务器上的数据库并压缩到指定目录,方便下载到本地而写本程序.配合windows的任务计划,可以达到定时备份数据库的目的. 程序需引用SQLDMO.DLL,如电脑上已安装sqlserv ...

  6. python字符串 常用函数 格式化字符串 字符串替换 制表符 换行符 删除空白 国际货币格式

    # 字符串常用函数# 转大写print('bmw'.upper()) # BMW# 转小写print('BMW'.lower()) # bmw# 首字母大写print('how aae you ?'. ...

  7. ASP.Net Web中Repeater怎么删除指定行

    使用OnItemCommand事件 首先附上相关的代码 <asp:Repeater ID="Repeater1" runat="server" OnIte ...

  8. Asp.net WebAPi gzip压缩和json格式化

    现在webapi越来越流行了,很多时候它都用来做接口返回json格式的数据,webapi原本是根据客户端的类型动态序列化为json和xml的,但实际很多时候我们都是序列化为json的,所以webapi ...

  9. Asp.Net Core IIS发布后PUT、DELETE请求错误405.0 - Method Not Allowed 因为使用了无效方法(HTTP 谓词)

    一.在使用Asp.net WebAPI 或Asp.Net Core WebAPI 时 ,如果使用了Delete请求谓词,本地生产环境正常,线上发布环境报错. 服务器返回405,请求谓词无效. 二.问题 ...

随机推荐

  1. ubuntu如何安装nodejs最新版 本

    如何正确的安装nodejs? 我们可以先安装nvm, git clone https://github.com/creationix/nvm.git ~/.nvm 然后打开 ~/.bashrc ,   ...

  2. 【HanLP】HanLP中文自然语言处理工具实例演练

    HanLP中文自然语言处理工具实例演练 作者:白宁超 2016年11月25日13:45:13 摘要:HanLP是hankcs个人完成一系列模型与算法组成的Java工具包,目标是普及自然语言处理在生产环 ...

  3. HTML5轻松实现搜索框提示文字点击消失---及placeholder颜色的设置

    在做搜索框的时候无意间发现html5的input里有个placeholder属性能轻松实现提示文字点击消失功能,之前还傻傻的在用js来实现类似功能... 示例 <form action=&quo ...

  4. Python爬虫小白入门(四)PhatomJS+Selenium第一篇

    一.前言 在上一篇博文中,我们的爬虫面临着一个问题,在爬取Unsplash网站的时候,由于网站是下拉刷新,并没有分页.所以不能够通过页码获取页面的url来分别发送网络请求.我也尝试了其他方式,比如下拉 ...

  5. C++ 拷贝构造函数和赋值运算符

    本文主要介绍了拷贝构造函数和赋值运算符的区别,以及在什么时候调用拷贝构造函数.什么情况下调用赋值运算符.最后,简单的分析了下深拷贝和浅拷贝的问题. 拷贝构造函数和赋值运算符 在默认情况下(用户没有定义 ...

  6. PHP设计模式(八)桥接模式(Bridge For PHP)

    一.概述 桥接模式:将两个原本不相关的类结合在一起,然后利用两个类中的方法和属性,输出一份新的结果. 二.案例 1.模拟毛笔(转) 需求:现在需要准备三种粗细(大中小),并且有五种颜色的比 如果使用蜡 ...

  7. PHP设计模式(七)适配器模式(Adapter For PHP)

    适配器模式:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作. 如下图(借图): // 设置书的接口 // 书接口 interface BookI ...

  8. 树莓派 基于Web的温度计

    前言:家里的树莓派吃灰很久,于是拿出来做个室内温度展示也不错. 板子是model b型. 使用Python开发,web框架是flask,温度传感器是ds18b20 1 硬件连接 ds18b20的vcc ...

  9. windows 7(32/64位)GHO安装指南(U盘引导篇)~

    上一篇我们说了怎么制作U盘启动盘,那么这一篇让我们来看看如何进行正确的U盘引导启动. 现在的个人计算机一般分为台式机和笔记本,由于各厂商的喜好不同(开玩笑的啦),所以对于主板的BIOS设置各所不同.进 ...

  10. oracle 存储过程

    来自:http://www.jb51.net/article/31805.htm Oracle存储过程基本语法 存储过程 1 CREATE OR REPLACE PROCEDURE 存储过程名 2 I ...