gpt4 book ai didi

c# - 重新发送 HttpRequestMessage - 异常

转载 作者:IT王子 更新时间:2023-10-29 04:21:06 26 4
gpt4 key购买 nike

我想多次发送完全相同的请求,例如:

HttpClient client = new HttpClient();
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, "http://example.com");

await client.SendAsync(req, HttpCompletionOption.ResponseContentRead);
await client.SendAsync(req, HttpCompletionOption.ResponseContentRead);

第二次发送请求将抛出异常并显示消息:

The request message was already sent. Cannot send the same requestmessage multiple times.

有没有办法“克隆”请求以便我可以再次发送?

我的真实代码在 HttpRequestMessage 上设置的变量比上面的示例更多,例如 header 和请求方法等变量。

最佳答案

我编写了以下扩展方法来克隆请求。

public static HttpRequestMessage Clone(this HttpRequestMessage req)
{
HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri);

clone.Content = req.Content;
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;
}

关于c# - 重新发送 HttpRequestMessage - 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18000583/

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