0

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

1 回答 1

2

您想对响应正文做什么?

此回调在第一次写入时调用,因此替换流为时已晚。您也无法从响应流中读取,因为它通常没有存储任何内容。这通常是输出到网络的只写流。

更早替换响应流是这里的正确方法。

于 2013-07-16T17:10:27.283 回答