这个问题与优素福的出色回答有关。我喜欢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);
    }
}