How do I compress a Json result from ASP.NET MVC with IIS 7.5

前端 未结 5 691
春和景丽
春和景丽 2021-01-30 00:22

I\'m having difficulty making IIS 7 correctly compress a Json result from ASP.NET MVC. I\'ve enabled static and dynamic compression in IIS. I can verify with Fiddler that normal

相关标签:
5条回答
  • 2021-01-30 00:36

    I have successfully used the approach highlighted here.

    0 讨论(0)
  • 2021-01-30 00:38

    The ActionFilterAttribute approach updated for ASP.NET 4.x and Includes Brotli.NET package.

    using System;
    using System.IO.Compression;
    using Brotli;
    using System.Web;
    using System.Web.Mvc;
    
    
    public class CompressFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;
    
            string acceptEncoding = request.Headers["Accept-Encoding"];
            if (string.IsNullOrEmpty(acceptEncoding)) return;
    
            acceptEncoding = acceptEncoding.ToUpperInvariant();
            HttpResponseBase response = filterContext.HttpContext.Response;
    
            if (acceptEncoding.Contains("BR"))
            {
                response.AppendHeader("Content-encoding", "br");
                response.Filter = new BrotliStream(response.Filter, CompressionMode.Compress);
            }
            else 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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-30 00:47

    I recommend this approach
    Create CompressAttribute class, and set target action.

    0 讨论(0)
  • 2021-01-30 00:49

    Make sure your %WinDir%\System32\inetsrv\config\applicationHost.config contains these:

    <system.webServer>
        <urlCompression doDynamicCompression="true" />
        <httpCompression>
          <dynamicTypes>
            <add mimeType="application/json" enabled="true" />
            <add mimeType="application/json; charset=utf-8" enabled="true" />       
          </dynamicTypes>
        </httpCompression>
    </system.webServer>
    

    From the link of @AtanasKorchev.

    As @simon_weaver said in the comments, you might be editing the wrong file with a 32 bit editor on a 64 bit Windows, use notepad.exe to make sure this file is indeed modified.

    0 讨论(0)
  • 2021-01-30 00:54

    Use this guide

    None of these answers worked for me. I did take note of the application/json; charset=utf-8 mime-type though.

    0 讨论(0)
提交回复
热议问题