我想多次发送完全相同的请求,例如:
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);
再次发送请求将引发以下消息异常:
他们可以“克隆”请求以便再次发送吗?
与上面的示例相比,我的真实代码在
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/