gpt4 book ai didi

asp.net-core - 如何检索当前响应正文长度?

转载 作者:行者123 更新时间:2023-12-02 18:01:57 25 4
gpt4 key购买 nike

我需要检索响应正文长度。

当我查看https://github.com/aspnet/HttpAbstractions/wiki/Rolling-Notes-Response-Stream-Contract时据说:

Stream.Position {get} and Stream.Length {get} return cumulative bytes written

这正是我所需要的,但是 httpContext.Response.Body.Length 引发 NotSupportedException 并显示“该流不可查找。”

我应该使用委托(delegate)流来计算每次写入的字节数吗?

最佳答案

我假设您正在尝试从中间件中获取 ContentLength?

这是一个中间件示例。应在任何响应生成中间件(例如 useMVC 或 useStaticFiles)之前将其添加到管道 (startup.cs)。

public class ContentLengthMiddleware
{
RequestDelegate _next;

public ContentLengthMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
using (var buffer = new MemoryStream())
{
var request = context.Request;
var response = context.Response;

var bodyStream = response.Body;
response.Body = buffer;

await _next(context);
Debug.WriteLine($"{request.Path} ({response.ContentType}) Content-Length: {response.ContentLength ?? buffer.Length}");
buffer.Position = 0;
await buffer.CopyToAsync(bodyStream);
}
}
}

出于超出我理解的原因,在返回静态文件(png、js等)时,响应正文将为空,但是设置了 ContentLength,这就是我使用 response.ContentLength 的原因? buffer.Length.

(mod注意:很抱歉两个问题的答案重复。另一个答案发布错误,打开了太多选项卡。我删除了它并在此处重新发布了答案)。

关于asp.net-core - 如何检索当前响应正文长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30652138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com