How to clone a HttpRequestMessage when the original request has Content?

后端 未结 2 1802
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 09:36

I\'m trying to clone a request using the method outlined in this answer: https://stackoverflow.com/a/18014515/406322

However, I get an ObjectDisposedException, if th

2条回答
  •  感动是毒
    2020-12-09 10:36

    If you call LoadIntoBufferAsync on the content, you can guarantee that the content is buffered inside the HttpContent object. The only problem remaining is that reading the stream does not reset the position, so you need to ReadAsStreamAsync and set the stream Position = 0.

    My example is very similar to the one Carlos showed...

     private async Task CloneResponseAsync(HttpResponseMessage response)
            {
                var newResponse = new HttpResponseMessage(response.StatusCode);
                var ms = new MemoryStream();
    
                foreach (var v in response.Headers) newResponse.Headers.TryAddWithoutValidation(v.Key, v.Value);
                if (response.Content != null)
                {
                    await response.Content.CopyToAsync(ms).ConfigureAwait(false);
                    ms.Position = 0;
                    newResponse.Content = new StreamContent(ms);
    
                    foreach (var v in response.Content.Headers) newResponse.Content.Headers.TryAddWithoutValidation(v.Key, v.Value);
    
                }
                return newResponse;
            }
    

    ```

提交回复
热议问题