asp.net implementation code to compress and remove blank HTML requests using HttpModule _ Practical Tips

Source: Internet
Author: User
And we can also remove some whitespace
Paragraphs, blank lines, comments, and so on to make the size of the HTML document smaller. Let's first implement the compression and deletion of whitespace classes, inheriting from the Stream class:
Copy Code code as follows:

<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 (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
}

The code above uses regular expressions to replace strings, and you can modify those regular expressions to suit your needs. We also use GZipStream and deflatestream to achieve compression. OK, next with
HttpModule combination:
Copy Code code as follows:

<summary>
Compresswhitespacemodule
</summary>
public class Compresswhitespacemodule:ihttpmodule
{
#region IHttpModule Members
<summary>
Disposes of the (other than memory) used by the module, that implements <see "cref=" E "/&GT;.
</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 a 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 the event containing
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
}

The Httpapplication.beginrequest event occurs as the first event in an HTTP execution pipeline chain when ASP.net responds to a request.
In web.config you also need to configure:
Copy Code code as follows:


<add name= "Compresswhitespacemodule" type= "Myweb.compresswhitespacemodule"/>


Let's take a look at the effect, below when not in use, 4.8KB

Then look, the effect after the treatment, Cotent-encoding:gzip, filezie:1.6kb

Quite simply, you can add more functionality as needed. Hope to be helpful to your development.
Author: Petter Liu

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.