这个问题与优素福的优秀answer有关。我喜欢OnSendingHeaders
回调。我现在可以添加响应头而不必担心切换流。无论如何,这是我的问题。是否可以在回调中读取响应主体,如此。
public override async Task Invoke(OwinRequest request, OwinResponse response)
{
request.OnSendingHeaders(state =>
{
var resp = (OwinResponse)state;
// Here, I want to convert resp, which is OwinResponse
// to HttpResponseMessage so that when Content.ReadAsStringAsync
// is called off this HttpResponseMessage object, I want the
// response body as string.
var responseMessage = new HttpResponseMessage();
responseMessage.Content = new StreamContent(resp.Body);
// Here I would like to call
// responseMessage.Content.ReadAsStringAsync()
}, response);
await Next.Invoke(request, response);
}
我想从回调中调用的方法是依赖HttpResponseMessage
并且不想更改它们的类的一部分。
如果我在流水线处理开始之前将响应主体设置为内存流(正如Youssef最初在链接的答案中所建议的那样),我能够实现这一点。有没有更好的方法在回调中执行此操作而不是?
编辑:
这可以吗?
public override async Task Invoke(OwinRequest request, OwinResponse response)
{
// Do something with request
Stream originalStream = response.Body;
var buffer = new MemoryStream();
response.Body = buffer;
await Next.Invoke(request, response);
var responseMessage = new HttpResponseMessage();
response.Body.Seek(0, SeekOrigin.Begin);
responseMessage.Content = new StreamContent(response.Body);
// Pass responseMessage to other classes for the
// response body to be read like this
// responseMessage.Content.ReadAsStringAsyn()
// Add more response headers
if (buffer != null && buffer.Length > 0)
{
buffer.Seek(0, SeekOrigin.Begin);
await buffer.CopyToAsync(originalStream);
}
}
答案 0 :(得分:1)
你想对回应团体做什么?
在第一次写入时调用此回调,因此替换流为时已晚。您也无法从响应流中读取,因为它通常没有存储任何内容。这通常是一个写入网络的只写流。
此处更换响应流是正确的方法。