ASP.NET Core压缩中间件

编程入门 行业动态 更新时间:2024-10-25 12:24:08
本文介绍了ASP.NET Core压缩中间件-空响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用此存储库中的一些自定义压缩中间件(粘贴在下面).根据第一个请求,内容将被压缩.对于此后的每个请求,响应都将返回为完全空(Content-Length为0).

I am using some custom compression middleware from this repository (pasted below). Upon the first request, the content is compressed just fine. For every request after that, the response comes back as completely empty (with a Content-Length of 0).

这只有在从ASP.NET Core RC2迁移到RTM之后才开始发生.

This only started happening after migrating from ASP.NET Core RC2 to RTM.

有人知道为什么会这样吗?

Does anyone know why this is happening?

CompressionMiddleware:

public class CompressionMiddleware { private readonly RequestDelegate _next; public CompressionMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { if (IsGZipSupported(context)) { string acceptEncoding = context.Request.Headers["Accept-Encoding"]; var buffer = new MemoryStream(); var stream = context.Response.Body; context.Response.Body = buffer; await _next(context); if (acceptEncoding.Contains("gzip")) { var gstream = new GZipStream(stream, CompressionLevel.Optimal); context.Response.Headers.Add("Content-Encoding", new[] { "gzip" }); buffer.Seek(0, SeekOrigin.Begin); await buffer.CopyToAsync(gstream); gstream.Dispose(); } else { var gstream = new DeflateStream(stream, CompressionLevel.Optimal); context.Response.Headers.Add("Content-Encoding", new[] { "deflate" }); buffer.Seek(0, SeekOrigin.Begin); await buffer.CopyToAsync(gstream); gstream.Dispose(); } } else { await _next(context); } } public bool IsGZipSupported(HttpContext context) { string acceptEncoding = context.Request.Headers["Accept-Encoding"]; return !string.IsNullOrEmpty(acceptEncoding) && (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")); } }

推荐答案

我在"添加HTTP压缩中间件"问题:

我添加了gzip,它可以正常工作,但是第一个请求.我的意思是在第一个请求中,响应页面为null(context.Response.Body),但是当您刷新页面(仅一次)后,它便可以正常工作了(我不知道为什么,但我必须解决它)/em>

I have added gzip and it worked, but first request. I mean in the first request, the response page is null (context.Response.Body) but when you refresh the page (just once) it works correctly after that.(I don't know why but I have to solve it)

问题的答案是:

您需要更新 实际压缩的context.Response.Headers ["Content-Length"] 缓冲区长度.

You need to update context.Response.Headers["Content-Length"] with actual compressed buffer length.

CompressionMiddleware.cs

上面压缩中间件的实现链接包含:

And above link to realisation of compression middleware contains:

if (context.Response.Headers["Content-Length"].Count > 0) { context.Response.Headers["Content-Length"] = compressed.Length.ToString(); }

更多推荐

ASP.NET Core压缩中间件

本文发布于:2023-11-05 09:47:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件   ASP   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!