首页 > 编程语言 >在Asp.Net WebApi中使用DotNetZip压缩响应流过滤器

在Asp.Net WebApi中使用DotNetZip压缩响应流过滤器

时间:2022-12-16 17:35:24浏览次数:41  
标签:WebApi DotNetZip Asp return bytes System actionExecutedContext var using

using Ionic.Zlib;
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace WebAPI.Filters
{
    /// <summary>
    /// 压缩返回信息
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class CompressionFilter : ActionFilterAttribute
    {
        public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            if (actionExecutedContext.Response == null || actionExecutedContext.Request.Method == HttpMethod.Options)
            {
                return DefaultResult(actionExecutedContext, cancellationToken);
            }
            var content = actionExecutedContext.Response.Content;
            if (content == null)
            {
                return DefaultResult(actionExecutedContext, cancellationToken);
            }
            var acceptEncoding = actionExecutedContext.Request.Headers.AcceptEncoding.Where(x => x.Value == "gzip" || x.Value == "deflate").ToList();
            if (acceptEncoding.Count == 0)
            {
                return DefaultResult(actionExecutedContext, cancellationToken);
            }
            var bytes = content.ReadAsByteArrayAsync();
            switch (acceptEncoding[0].Value)
            {
                case "gzip":
                    actionExecutedContext.Response.Content = new ByteArrayContent(CompressionHelper.GZipBytes(bytes.Result));
                    actionExecutedContext.Response.Content.Headers.Add("Content-Encoding", "gzip");
                    break;
                case "deflate":
                    actionExecutedContext.Response.Content = new ByteArrayContent(CompressionHelper.DeflateBytes(bytes.Result));
                    actionExecutedContext.Response.Content.Headers.Add("Content-encoding", "deflate");
                    break;
            }
            return DefaultResult(actionExecutedContext, cancellationToken);
        }
        private Task DefaultResult(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
        }
    }

    /// <summary>
    /// 压缩帮助类
    /// </summary>
    internal static class CompressionHelper
    {
        public static byte[] DeflateBytes(byte[] bytes)
        {
            if (bytes.Length == 0)
            {
                return null;
            }
            using (var output = new MemoryStream())
            {
                using (var compressor = new  DeflateStream(output, CompressionMode.Compress, CompressionLevel.Default))
                {
                    compressor.Write(bytes, 0, bytes.Length);
                }
                return output.ToArray();
            }
        }

        public static byte[] GZipBytes(byte[] bytes)
        {
            if (bytes.Length == 0)
            {
                return null;
            }
            using (var output = new MemoryStream())
            {
                using (var compressor = new GZipStream(output, CompressionMode.Compress, CompressionLevel.Default))
                {
                    compressor.Write(bytes, 0, bytes.Length);
                }
                return output.ToArray();
            }
        }
    }
}

  

标签:WebApi,DotNetZip,Asp,return,bytes,System,actionExecutedContext,var,using
From: https://www.cnblogs.com/5tomorrow/p/16987911.html

相关文章

  • asp.net model 校验列表
    [ArgumentIsNullOrWhitespace,Theargument'{0}'cannotbenull,emptyorcontainonlywhitespace.][AssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsU......
  • Asp.Net上传文件示例(保存文件路径到数据库)
    把下面的代码保存为Upload.aspx即可运行(事先在同目录下建立一个Upload文件夹保存上传的文件,再建立一个数据库、表Upload,字段ID:自动编号,FilePath:文本型):<%@ImportName......
  • 动态载入树 (ASP+数据库)
    ASP+ACCESS在数据量达100万条记录下,载入速度仍然惊人....//网上转载.忘了作者... :)//********************** Index.asp************************//1<%@LAN......
  • asp.net发送邮件
    1.SMTP邮件传输协议 SMTP的全称是“SimpleMailTransferProtocol”,即简单邮件传输协议。它是一组用于从源地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式。SMT......
  • [C#] Asp.net Core SignalR 跨域设置
    参考:https://blog.csdn.net/hefeng_aspnet/article/details/117777995?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7E......
  • aspx.net开源的画图组件
    官网 ​​http://www.carlosag.net/Tools/WebChart/sampleStacked.aspx​​中文简介:​​http://www.51aspx.com/CT/VRIBNJDPXLY20/​​作者:沐雪​​​......
  • 做了MVC模式一年,可不要把传统模式忘记呀!ashx配合aspx实现AJAX加载JSON数据
    ASHX内容:#regionIHttpHandlerMemberspublicvoidProcessRequest(HttpContextcontext){context.Response.ContentType="application/x......
  • WebApi Autofac依赖注入配置
    publicclassAutofacConfig{///<summary>///IOC注册///</summary>publicstaticvoidRegister(){......
  • 创建一个WebApi项目
    原文链接:https://www.bilibili.com/video/BV12L4y1b7ND/?spm_id_from=333.337.search-card.all.click&vd_source=23aa9dcacf4c7ddaed4172b5ffd451ab创建一个WebApi大致分......
  • ASP.NET Core 奇淫技巧之动态WebApi
    一.前言接触到动态WebApi(DynamicWebAPI)这个词的已有几年,是从ABP框架里面接触到的,当时便对ABP的这个技术很好奇,后面分析了一波,也尝试过从ABP剥离一个出来作为独立组件来使......