gpt4 book ai didi

c# - 当原始请求有内容时如何克隆 HttpRequestMessage?

转载 作者:可可西里 更新时间:2023-11-01 08:18:01 26 4
gpt4 key购买 nike

我正在尝试使用此答案中概述的方法克隆请求: https://stackoverflow.com/a/18014515/406322

但是,如果原始请求有内容,我会得到一个 ObjectDisposedException。

如何可靠地克隆 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
foreach (var h in req.Content.Headers)
clone.Content.Headers.Add(h.Key, h.Value);
}


clone.Version = req.Version;

foreach (KeyValuePair<string, object?> option in req.Options)
clone.Options.Set(new HttpRequestOptionsKey<object?>(option.Key), option.Value);

foreach (KeyValuePair<string, IEnumerable<string>> header in req.Headers)
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);

return clone;
}

关于c# - 当原始请求有内容时如何克隆 HttpRequestMessage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25044166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com