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

后端 未结 2 1803
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 10:20

    This should do the trick:

        public static async Task CloneHttpRequestMessageAsync(HttpRequestMessage req)
        {
            HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri);
    
            // Copy the request's content (via a MemoryStream) into the cloned object
            var ms = new MemoryStream();
            if (req.Content != null)
            {
                await req.Content.CopyToAsync(ms).ConfigureAwait(false);
                ms.Position = 0;
                clone.Content = new StreamContent(ms);
    
                // Copy the content headers
                if (req.Content.Headers != null)
                    foreach (var h in req.Content.Headers)
                        clone.Content.Headers.Add(h.Key, h.Value);
            }
    
    
            clone.Version = req.Version;
    
            foreach (KeyValuePair prop in req.Properties)
                clone.Properties.Add(prop);
    
            foreach (KeyValuePair> header in req.Headers)
                clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
    
            return clone;
        }
    

提交回复
热议问题