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?