大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > ASP.NET技巧 > ASP.Net实现GZip压缩功能代码

ASP.Net实现GZip压缩功能代码

关键词:ASP.NetGZip压缩代码  阅读(935) 赞(60)

[摘要]ASP.Net实现GZip压缩,需要修改Global文件, 给response设置压缩的Filter。

.Net实现GZip压缩,需要修改Global文件, 给response设置压缩的Filter。

首先添加引用:

using System.IO.Compression;
using System.Web;

然后在Global文件添加下列代码:

private void Application_BeginRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;
            var request = context.Request;
            var response = context.Response;
            ResponseCompressionType compressionType = this.GetCompressionMode(request);

            if (compressionType != ResponseCompressionType.None)
            {
                response.AppendHeader("Content-Encoding", compressionType.ToString().ToLower());
                if (compressionType == ResponseCompressionType.GZip)
                {
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                }
                else
                {
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                }
            }
        }

        private ResponseCompressionType GetCompressionMode(HttpRequest request)
        {
            string acceptEncoding = request.Headers["Accept-Encoding"];
            if (string.IsNullOrEmpty(acceptEncoding))
            {
                return ResponseCompressionType.None;
            }
            acceptEncoding = acceptEncoding.ToUpperInvariant();
            if (acceptEncoding.Contains("GZIP"))
            {
                return ResponseCompressionType.GZip;
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                return ResponseCompressionType.Deflate;
            }
            else
            {
                return ResponseCompressionType.None;
            }
        }
        private enum ResponseCompressionType { None, GZip, Deflate }



相关评论