无法使用Func <HttpRequestMessage>

时间:2019-06-04 17:52:45

标签: c# api asp.net-core asp.net-core-webapi

我们的API具有重试逻辑,用于调用另一个端点。但这给我一个

的错误
  

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

这是我的代码

public async Task<object> GetResponse()
{
    var httpRequestMessage = ConstructHttpRequestForBatchUpdate(batchRequest, client, requestUri);
    HttpResponseMessage httpResponseMessage = await _retryHttpRequest.ExecuteAsync(() => httpRequestMessage, client, maxRetryValue);
}

private HttpRequestMessage ConstructHttpRequestForBatchUpdate(JArray batchRequest, HttpClient client, Uri requestUri)
{
    var batchReqStr = JsonConvert.SerializeObject(batchRequest);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var httpRequestMessage = new HttpRequestMessage()
    {
        Content = new StringContent(batchReqStr, Encoding.UTF8, "application/json"),
        Method = HttpMethod.Put,
        RequestUri = requestUri
    };
    return httpRequestMessage;
}


public class RetryHttpRequest : IRetryHttpRequest
{
    public async Task<HttpResponseMessage> ExecuteAsync(Func<HttpRequestMessage> requestMessage, HttpClient client, int maxTryValue)
    {
        var remainingTries = maxTryValue;
        var exceptions = new List<Exception>();
        do
        {
            --remainingTries;
            try
            {
                return await ExecuteSingleAsync(requestMessage(), client);
            }
            catch (Exception e)
            {
                exceptions.Add(e);
            }
        }
        while (remainingTries > 0);
        throw new AggregateException(exceptions);
    }
    public async Task<HttpResponseMessage> ExecuteSingleAsync(HttpRequestMessage requestMessage, HttpClient client)
    {
        try
        {
            HttpResponseMessage httpResponseMessage = await client.SendAsync(requestMessage);
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                return httpResponseMessage;
            }
            else
            {
                var exception = new InvalidOperationException();
                throw new Exception();
            }
        }
        catch (HttpRequestException httpException)
        {
            throw httpException;
        }
    }
}

据我所知,Func<HttpRequestMessage>允许它创建HttpRequestMessage的新实例。例如,对于这一行代码

return await ExecuteSingleAsync(requestMessage(), client);

requestMessage()正在为每个循环创建一个新实例。但是,如果我的理解是正确的,我不确定为什么它仍然给我发送相同请求的错误。

1 个答案:

答案 0 :(得分:4)

  

requestMessage()正在为每个循环创建一个新实例。

情况并非如此-您提交的Func是() => httpRequestMessage,它总是返回相同的实例。

尝试以下方法:

_retryHttpRequest.ExecuteAsync(() => ConstructHttpRequestForBatchUpdate(batchRequest, client, requestUri), client, maxRetryValue);