如何克隆HttpRequestMessage当原来的请求有内容? [英] How to clone a HttpRequestMessage when the original request has Content?
本文介绍了如何克隆HttpRequestMessage当原来的请求有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想克隆使用这个答案概括的方法的请求:
http://stackoverflow.com / A /四十零万六千三百二十二分之一千八百〇一万四千五百一十五
I'm trying to clone a request using the method outlined in this answer: http://stackoverflow.com/a/18014515/406322
不过,我得到一个的ObjectDisposedException,如果原始请求已经收到的内容。
However, I get an ObjectDisposedException, if the original request has content.
你怎么能可靠地克隆HttpRequestMessage
How can you reliably clone a HttpRequestMessage?
推荐答案
这应该做的伎俩:
public static async Task<HttpRequestMessage> 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<string, object> prop in req.Properties)
clone.Properties.Add(prop);
foreach (KeyValuePair<string, IEnumerable<string>> header in req.Headers)
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
return clone;
}
这篇关于如何克隆HttpRequestMessage当原来的请求有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文