重新发送的Htt prequestMessage - 异常异常、Htt、prequestMessage

2023-09-03 06:47:43 作者:以治丧丧

我想发完全相同的请求不止一次,例如:

I want to send the exact same request more than once, for example:

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);

发送第二次请求将引发异常的消息:

Sending the request for a second time will throw an exception with the message:

请求消息已经发出。无法发送相同的请求   消息多次。

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

是他们的一种方式的克隆的的要求,这样我可以重新发送?

Is their a way to "clone" the request so that I can send again?

我真正的code对设置更多的变量的Htt prequestMessage 比在上面的例子中,类似的报头和请求的方法变量。

My real code has more variables set on the HttpRequestMessage than in the example above, variables like headers and request method.

推荐答案

我写了下面的扩展方法克隆的要求。

I wrote the following extension method to clone the request.

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;
}