ASP.NET Web Api 的响应数据压缩gzip/deflate

首先一张图看懂ASP.NET

 

写一个ActionFilter来实现GZIP:ActionFilter的介绍

web api ApiController:


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;
using System.IO.Compression;
using System.Net.Http;

namespace Mizusho.OA.WebApi.Utils
{
    public class CompressAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var content = actionExecutedContext.Response.Content;
            var acceptEncoding = actionExecutedContext.Request.Headers.AcceptEncoding.Where(x => x.Value == "gzip" || x.Value == "deflate").ToList();
            if (acceptEncoding != null && acceptEncoding.Count > 0 && content != null && actionExecutedContext.Request.Method != HttpMethod.Options)
            {
                var bytes = content.ReadAsByteArrayAsync().Result;
                if (acceptEncoding.FirstOrDefault().Value == "gzip")
                {
                    actionExecutedContext.Response.Content = new ByteArrayContent(CompressionHelper.GzipCompress(bytes));
                    actionExecutedContext.Response.Content.Headers.Add("Content-Encoding", "gzip");
                }
                else if (acceptEncoding.FirstOrDefault().Value == "deflate")
                {
                    actionExecutedContext.Response.Content = new ByteArrayContent(CompressionHelper.DeflateCompress(bytes));
                    actionExecutedContext.Response.Content.Headers.Add("Content-encoding", "deflate");
                }
            }
            base.OnActionExecuted(actionExecutedContext);
        }

    }
    class CompressionHelper
    {

        public static byte[] DeflateCompress(byte[] data)
        {
            if (data == null || data.Length < 1)
                return data;
            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    using (DeflateStream gZipStream = new DeflateStream(stream, CompressionMode.Compress))
                    {
                        gZipStream.Write(data, 0, data.Length);
                        gZipStream.Close();
                    }
                    return stream.ToArray();
                }
            }
            catch (Exception)
            {
                return data;
            }
        }

        public static byte[] GzipCompress(byte[] data)
        {
            if (data == null || data.Length < 1)
                return data;
            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress))
                    {
                        gZipStream.Write(data, 0, data.Length);
                        gZipStream.Close();
                    }
                    return stream.ToArray();
                }
            }
            catch (Exception)
            {
                return data;
            }

        }
    }
}

用法:

在controller文件中
       [CompressFilter]
        public class XXXController : ApiController
       {
           
       }

 

MVC Controller:

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 classCompressFilterAttribute:ActionFilterAttribute
    {
       public override void OnResultExecuting(ResultExecutingContextfilterContext)
       {
           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();
       }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值