我需要检索响应体长度.
当我看到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.