您的位置:首页 > 编程语言 > ASP

ASP.NET MVC 简单实现GZIP

2020-03-01 12:56 155 查看

   一般页面不会太大的,通常都不需要用到GZIP,但是某些情况下还是需要GZIP来压缩的,现在呢,介绍一种在ASP.NET MVC下的GZIP压缩方法...

 

   写一个ActionFilter来实现GZIP:

CompressFilterAttribute.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.IO.Compression;

namespace MyMVC.ActionFilters
{
    public class CompressFilterAttribute:ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            string acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
            if (String.IsNullOrEmpty(acceptEncoding)) return;
            var response = filterContext.HttpContext.Response;
            acceptEncoding = acceptEncoding.ToUpperInvariant();

            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);
            }
        }
    }
}

 

在controller文件中


        [CompressFilter]
        public ActionResult Compress()
        {
            return this.View();
        }

 

实例:(截图)

压缩前

压缩后

压缩量可以达到百分之九十多...

 

实在是方便!!!

转载于:https://www.cnblogs.com/XYZPark/p/5010116.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
ZQQQ1112 发布了0 篇原创文章 · 获赞 0 · 访问量 7 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: