4

I have a method that sends POST requests to a server. The request is defined in the HttpRequestMessage object.

Yet, if the server returns some retryable error, I would like to retry, as the following code does:

using (var request = new HttpRequestMessage(HttpMethod.Post, _endpoint))
{
    var requestPayload = Serialize(ingestionRequest);
    request.Content = new StringContent(requestPayload, Encoding.UTF8, JsonContentType);

    await _retryPolicy.ExecuteAsync(async () =>
    {
        // ReSharper disable once AccessToDisposedClosure
        using (var response = await _httpClient.SendAsync(request))
        {
            if (!response.IsSuccessStatusCode)
            {
                throw new IngestionException(response.StatusCode, response.ReasonPhrase);
            }
        }
    });
}

It turns out that an HttpRequestMessage cannot be sent more than once, throwing the following exception:

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

How could I do what's the above code tries to do - while keeping the code simple and elegant?

johni
  • 5,342
  • 6
  • 42
  • 70

1 Answers1

1

Try copying/cloning the request message using something like this answer. Then use the cloned request on the next retry. Something like

if (!response.IsSuccessStatusCode)
{
  var oldRequest = request;
  request = request.Clone();
  oldRequest.Dispose();
  throw new IngestionException(response.StatusCode, response.ReasonPhrase);
}
Community
  • 1
  • 1
Jim Gilmartin
  • 783
  • 6
  • 13