. Net mvc simple implementation GZIP

Source: Internet
Author: User

We all know the benefits of GZIP, but in general, the page is not too big, and many people have not paid attention to this. Some time ago, I made a system using a JQUERY rich client framework developed by a Chinese people (I personally think this framework is quite good), similar to the AJAX framework of EXT, the JS of the framework, coupled with my own, is really not small.

 

 

I plan to use GZIP for compression. I have done it on IIS6 before. This project is implemented using MVC and found in. net mvc has a simpler and easier way to solve the problem: Write an ActionFilter to implement GZIP. You will know the advantages when you use it.

 

    public class CompressAttribute : ActionFilterAttribute    {        public override void OnActionExecuting(ActionExecutingContext filterContext)        {            var acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];            if (!string.IsNullOrEmpty(acceptEncoding))            {                acceptEncoding = acceptEncoding.ToLower();                var response = filterContext.HttpContext.Response;                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);                }            }        }    }

Usage:

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

You only need to write [Compress] on the Action to be compressed using GZIP. Is it very simple ~

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.