我正在尝试编写一个简单的OWIN中间件,以拦截响应流。我想要做的是用自定义的基于 Stream 的类替换原始流,在那里我将能够拦截对响应流的写入。
但是,我遇到了一些问题,因为我不知道响应何时被链中的内部中间件组件完全写入。永远不会调用 Stream的Dispose
覆盖。所以我不知道什么时候该执行我的处理,这应该发生在响应流的末尾。
这是一个示例代码:
public sealed class CustomMiddleware: OwinMiddleware
{
public CustomMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
var request = context.Request;
var response = context.Response;
// capture response stream
var vr = new MemoryStream();
var responseStream = new ResponseStream(vr, response.Body);
response.OnSendingHeaders(state =>
{
var resp = (state as IOwinContext).Response;
var contentLength = resp.Headers.ContentLength;
// contentLength == null for Chunked responses
}, context);
// invoke the next middleware in the pipeline
await Next.Invoke(context);
}
}
public sealed class ResponseStream : Stream
{
private readonly Stream stream_; // MemoryStream
private readonly Stream output_; // Owin response
private long writtenBytes_ = 0L;
public ResponseStream(Stream stream, Stream output)
{
stream_ = stream;
output_ = output;
}
... // System.IO.Stream implementation
public override void Write(byte[] buffer, int offset, int count)
{
// capture writes to the response stream in our local stream
stream_.Write(buffer, offset, count);
// write to the real output stream
output_.Write(buffer, offset, count);
// update the number of bytes written
writtenBytes_ += count;
// how do we know the response is complete ?
// we could check that the number of bytes written
// is equal to the content length, but content length
// is not available for Chunked responses.
}
protected override void Dispose(bool disposing)
{
// we could perform our processing
// when the stream is disposed of.
// however, this method is never called by
// the OWIN/Katana infrastructure.
}
}
正如我在上面代码的注释中提到的那样,我可以想到两种策略来检测响应是否完整。
a) 我可以记录写入响应流的字节数并将其与预期的响应长度相关联。然而,在使用分块传输编码的响应的情况下,长度是未知的。
b)我可以决定在响应流Dispose
上调用时响应流是完整的。但是,OWIN/Katana 基础结构从不对替换的流调用 Dispose。
我一直在研究Opaque Streaming以查看操作底层 HTTP 协议是否是一种可行的方法,但我似乎没有发现 Katana 是否支持 Opaque Streaming。
有没有办法实现我想要的?