繁体   English   中英

在 asp.net mvc 中使用 C# 解压缩正文请求,已使用 pako 库 JS 压缩

[英]Decompress body request with C# in asp.net mvc already compressed with pako library JS

我有一个 asp.net mvc 应用程序,想使用 Pako 库(使用 gzip 和 deflate 编码)压缩视图中的请求正文,并在使用 OnActionExecuting 和 GZipStream/DeflateStream 到达控制器之前解压缩正文请求。

为什么要这样做? 因为我有一个阻止所有请求 > 128KB 的防火墙,所以我在必要时进行压缩,我已经使用 angular 10 和 .NET Core API 中的另一个应用程序这样做了,但在 asp.net mvc 中不能做同样的事情:(

现在我可以压缩正文并使用 ajax 将其发送到控制器,触发 OnActionExecuting 但我的代码不起作用 request.Filtrer 通过但我在模型控制器中有 null 并且 filterContext.ActionParameters.Values 也是 null 。

我用 angular 10 和 API.NET Core 实现了这一点,它工作我在 angular 中使用了 pako,在我的 api 核心中使用了这段代码:

public async Task Invoke(HttpContext httpContext)
        {
            await SlowStuffSemaphore.WaitAsync();
            try
            {
                _httpContext = httpContext;
                bool isGzip = IsGzipRequest();
                if (isGzip)
                {
                    _httpContext.Request.Body = new GZipStream(_httpContext.Request.Body, CompressionMode.Decompress);
                }

                await _next.Invoke(_httpContext);
            }
            catch(ArgumentNullException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            finally
            {
                SlowStuffSemaphore.Release();
            }
        }  

  

我的 ASP.NET MVC 代码:

看法 :

  <script>
        window.SendZipedRequest = (reqbody) => {
        $.ajax({
        url: "/Home/AddAgency",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        type: "post",
        headers: { "Content-Encoding": "gzip" },
        data: pako.gzip(JSON.stringify(reqbody), {to: "string"}),
        beforeSend: function (data) {
        //Do Something
        },
        success: function (data, textStatus, jqXHR) {
        console.log('Yay!');
        //$("#content").html(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
        console.log('Oh no!');
        },
        complete: function (jqXHR, textStatus) {
        console.log(textStatus);
        console.log(jqXHR.status);
        //console.log(jqXHR.responseText);
        }
        });
        }
    </script>

动作过滤器属性:

public class CompressContentAttribute : ActionFilterAttribute
{
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
    HttpRequestBase request = filterContext.HttpContext.Request;
    request.Filter = new GZipStream(request.Filter, CompressionMode.Decompress);
    base.OnActionExecuting(filterContext);
 }
}

另一个问题我有它是 HttpContext.Request.InputStream (流包含我的身体)它是只读的

谢谢

.NET 7 Preview 6开始,ASP.NET Core 中添加了一个新的中间件,它使用 Content-Encoding HTTP 标头自动识别和解压缩带有压缩内容的请求,这样服务器的开发人员就不需要自己处理这个问题。 使用IApplicationBuilder UseRequestDecompression方法和IServiceCollection上的AddRequestDecompression扩展方法添加请求解压中间件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM