加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 04:05:27 所属栏目:asp.Net 来源:网络整理
导读:我需要检索响应体长度. 当我看到https://github.com/aspnet/HttpAbstractions/wiki/Rolling-Notes-Response-Stream-Contract时,据说: Stream.Position {get} and Stream.Length {get} return cumulative bytes written 这正是我需要的,但是httpContext.Resp
我需要检索响应体长度.

当我看到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,并说“该流不可搜索”.

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

解决方法

我假设您正在尝试从中间件中获取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:抱歉两个问题的重复答案.另一个答案是错误发布,打开了太多标签.我删除了它并在此处重新发布了答案).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读