Use http compression in ASP. NET

Source: Internet
Author: User

Compressing all pages through gzip or deflate will greatly reduce the page transfer capacity.

You can use fiddler2 to observe the page size changes after compression.

Add global. asax to the project and add the following code:

1 protected void application_beginrequest (Object sender, eventargs E)
2 {
3 httpapplication APP = (httpapplication) sender;
4 string acceptencoding = app. Request. headers ["Accept-encoding"];
5 stream prevuncompressedstream = app. response. filter;
6 if (acceptencoding = NULL | acceptencoding. Length = 0) return;
7 acceptencoding = acceptencoding. tolower ();
8 If (acceptencoding. Contains ("gzip "))
9 {
10 // Gzip
11 app. response. Filter = new gzipstream (prevuncompressedstream, compressionmode. Compress );
12 app. response. appendheader ("content-encoding", "gzip ");
13}
14 else if (acceptencoding. Contains ("deflate "))
15 {
16 // defalte
17 app. response. Filter = new deflatestream (prevuncompressedstream, compressionmode. Compress );
18 app. response. appendheader ("content-encoding", "deflate ");
19}
20}

 

 

Fixed:

This method was accidentally found on the Internet. I did not use it in my actual project. The compression effect is yes, but I have not tested the resource usage on the server, so it is not clear that this is better than setting compression methods in IIS. For the moment, we only need to back up the code, and we will study it with no space in the future.

In addition, this method has some disadvantages. I found in the experiment that using it will cause small icons of the Treeview that comes with. Net to become invalid. The reason is that when Treeview uses the default small icon, the image file uses webresource. after the axd is obtained, the image cannot be obtained after compression. Therefore, when the Code starts, the requested file is filtered and webresource is retrieved. axd is not compressed.

 

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.