Search code examples
c#.netdotnet-httpclient

Re-Send HttpRequestMessage - Exception


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 there a way to "clone" the request so that I can send again?

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


Solution

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