Asp.net使用HttpModule压缩并删除空白Html请求的实现代码_实用技巧

同时我们还可以删除一些空白
段,空行,注释等以使得HTML文档的尺寸变得更小. 让我们先来实现压缩与删除空白类, 继承自Stream类:

复制代码 代码如下:

/// <summary>
/// CompressWhitespaceFilter
/// </summary>
public class CompressWhitespaceFilter : Stream
{
private GZipStream _contentGZipStream;
private DeflateStream _content_DeflateStream;
private Stream _contentStream;
private CompressOptions _compressOptions;
/// <summary>
/// Initializes a new instance of the <see cref="CompressWhitespaceFilter"/> class.
/// </summary>
/// <param name="contentStream">The content stream.</param>
/// <param name="compressOptions">The compress options.</param>
public CompressWhitespaceFilter(Stream contentStream, CompressOptions compressOptions)
{
if (compressOptions == CompressOptions.GZip)
{
this._contentGZipStream = new GZipStream(contentStream, CompressionMode.Compress);
this._contentStream = this._contentGZipStream;
}
else if (compressOptions == CompressOptions.Deflate)
{
this._content_DeflateStream = new DeflateStream(contentStream,CompressionMode.Compress);
this._contentStream = this._content_DeflateStream;
}
else
{
this._contentStream = contentStream;
}
this._compressOptions = compressOptions;
}
public override bool CanRead
{
get { return this._contentStream.CanRead; }
}
public override bool CanSeek
{
get { return this._contentStream.CanSeek; }
}
public override bool CanWrite
{
get { return this._contentStream.CanWrite; }
}
public override void Flush()
{
this._contentStream.Flush();
}
public override long Length
{
get { return this._contentStream.Length; }
}
public override long Position
{
get
{
return this._contentStream.Position;
}
set
{
this._contentStream.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return this._contentStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return this._contentStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
this._contentStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
byte[] data = new byte[count + 1];
Buffer.BlockCopy(buffer, offset, data, 0, count);
string strtext = System.Text.Encoding.UTF8.GetString(data);
strtext = Regex.Replace(strtext, "^\\s*", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
strtext = Regex.Replace(strtext, "\\r\\n", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
strtext = Regex.Replace(strtext, "<!--*.*?-->", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
byte[] outdata = System.Text.Encoding.UTF8.GetBytes(strtext);
this._contentStream.Write(outdata, 0, outdata.GetLength(0));
}
}
/// <summary>
/// CompressOptions
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Zcat#gunzip_and_zcat"/>
/// <seealso cref="http://en.wikipedia.org/wiki/DEFLATE"/>
public enum CompressOptions
{
GZip,
Deflate,
None
}

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

复制代码 代码如下:

/// <summary>
/// CompressWhitespaceModule
/// </summary>
public class CompressWhitespaceModule : IHttpModule
{
#region IHttpModule Members
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
/// </summary>
public void Dispose()
{
// Nothing to dispose;
}
/// <summary>
/// Initializes a module and prepares it to handle requests.
/// </summary>
/// <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>
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
/// <summary>
/// Handles the BeginRequest event of the context control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app.Request.RawUrl.Contains(".aspx"))
{
HttpContext context = app.Context;
HttpRequest request = context.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
HttpResponse response = context.Response;
if (!string.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToUpperInvariant();
if (acceptEncoding.Contains("GZIP"))
{
response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.GZip);
response.AppendHeader("Content-encoding", "gzip");
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.Deflate);
response.AppendHeader("Content-encoding", "deflate");
}
}
response.Cache.VaryByHeaders["Accept-Encoding"] = true;
}
}
#endregion
}

HttpApplication.BeginRequest 事件是 在 ASP.NET 响应请求时作为 HTTP 执行管线链中的第一个事件发生。
在WEB.CONFIG中你还需要配置:

复制代码 代码如下:

<httpModules>
<add name="CompressWhitespaceModule" type="MyWeb.CompressWhitespaceModule" />
</httpModules>

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

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

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

时间: 2024-09-17 04:34:03

Asp.net使用HttpModule压缩并删除空白Html请求的实现代码_实用技巧的相关文章

Asp.net中安全退出时清空Session或Cookie的实例代码_实用技巧

概览: 网站中点击退出,如果仅仅是重定向到登录/出页面,此时在浏览器地址栏中输入登录后的某个页面地址如主页,你会发现不用登录就能访问.这种所谓的退出并不是安全的. 那么怎样做到安全退出呢? 那就是点击退出后清空相应的Session或Cookie. 清空Session的代码: Session.Clear(); Session.Abandon(); 清除Cookie的正确代码(假设Cookie名称为UserInfo): if (Request.Cookies["UserInfo"] !=

ASP.NET Gridview 中使用checkbox删除的2种方法实例分享_实用技巧

方法一:后台代码: 复制代码 代码如下:  protected void btn_delete_Click(object sender, EventArgs e)    {        for (int i = 0; i <this.GridView1.Rows.Count; i++)        {            int id = Convert.ToInt32(this.GridView1.DataKeys[i].Value);            if ((this.Grid

asp.net正则表达式删除指定的HTML标签的代码_实用技巧

如果全盘删除里面的 HTML 标签,可能会造成阅读上的困难(比如 a, img 这些标签), 最好是删除一部分,保留一部分. 正则表达式里,判断 包含某些字符串 是非常容易理解的,但是如何判断 不包含某些字符串 (是字符串,不是字符,是某些,不是某个) 确实是个费解的事. 复制代码 代码如下: <(?!((/?\s?li)|(/?\s?ul)|(/?\s?a)|(/?\s?img)|(/?\s?br)|(/?\s?span)|(/?\s?b)))[^>]+> 这个正则是判断HTML标签不

Repeater全选删除和分页实现思路及代码_实用技巧

复制代码 代码如下: <script type="text/javascript"> function SelectAll(box) { for(var i=0;i <document.form1.elements.length;i++) { var e=document.form1.elements[i]; if((e.type=='checkbox')) { var o=e.name.lastIndexOf('cbx'); if(o!=-1) { e.checke

asp.net实现上传文件显示本地绝对路径的实例代码_实用技巧

页面代码主要就是JSview plaincopy to clipboardprint 复制代码 代码如下: <head runat="server">     <title>无标题页</title>     <mce:script language="javascript" type="text/javascript"><!--      function Imagesrc()      { 

Asp.Net模拟表单提交数据和上传文件的实现代码_实用技巧

如果你需要跨域上传内容到另外一个域名并且需要获取返回值,使用Asp.Net的作为代理是最好的办法,要是客户端直接提交到iframe中,由于跨域是无法用javascript获取到iframe中返回的内容的.此时需要在自己的网站做一个动态页作为代理,将表单提交到动态页,动态页负责将表单的内容使用WebClient或HttpWebRequest将表单数据再上传到远程服务器,由于在服务器端进行操作,就不存在跨域问题了. WebClient上传只包含键值对的文本信息示例代码: 复制代码 代码如下: str

总结ASP.NET C#中经常用到的13个JS脚本代码_实用技巧

在C#开发过程中,免不了写一些JS,其实做后端开发的,本身不擅长写JS,干脆总结一下,方便自己也方便别人,分享给大家.呵呵~~ 1.按钮前后台事件 复制代码 代码如下: <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" OnClientClick="alert('客房端验证,阻止向服务器端提交');retu

ASP.NET Gridview与checkbox全选、全不选实现代码_实用技巧

1. 页面 在onclick事件中 "传自己" 复制代码 代码如下: <asp:TemplateField HeaderText="全选"> <HeaderTemplate> <input type="checkbox" id="CheckBox1" name="CheckBox1" onclick="GetAllCheckBox(this)" />

asp.net通过js实现Cookie创建以及清除Cookie数组的代码_实用技巧

复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="BLTZ.aspx.cs" Inherits="BLTZ" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1