相关疑难解决方法(0)

重新发送HttpRequestMessage - 异常

我想多次发送完全相同的请求,例如:

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);
Run Code Online (Sandbox Code Playgroud)

第二次发送请求将抛出异常消息:

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

他们是一种" 克隆 "请求的方式,以便我可以再次发送?

我的实际代码HttpRequestMessage在上面的示例中设置了更多变量,变量如header和request方法.

.net c# dotnet-httpclient

26
推荐指数
4
解决办法
1万
查看次数

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

我的代码在这里有什么问题吗?我一直收到这个错误:

System.InvalidOperationException:请求消息已发送.无法多次发送相同的请求消息.

我的HttpRequestMessage在Func中,所以我想我每次传入func()时都会得到一个全新的请求.

public async Task<HttpResponseMessage> GetAsync(HttpRequestMessage request)
{
     return await RequestAsync(() => request);
}

public async Task<HttpResponseMessage> RequestAsync(Func<HttpRequestMessage> func)
{
   var response = await ProcessRequestAsync(func);

    if (response.StatusCode == HttpStatusCode.Unauthorized)   
    {
        WaitForSomeTime();
        response = await ProcessRequestAsync(func);        
    }

    return response;
}

private async Task<HttpResponseMessage> ProcessRequestAsync(Func<HttpRequestMessage> func)
{
    var client = new HttpClient();
    var response = await client.SendAsync(func()).ConfigureAwait(false);
    return response;
}
Run Code Online (Sandbox Code Playgroud)

.net c# func async-await dotnet-httpclient

8
推荐指数
2
解决办法
1万
查看次数

使用 Polly 在 ASP.NET Core 中重试请求时出现“流已被消耗”错误

我有一个 ASP.NET Core 3.1 Web API 服务,它正在接收 Web 请求,对其进行一些操作,然后将其传递到后端服务并同步返回响应。它工作正常,但我想为这些后端请求引入一些重试逻辑,以防出现一些问题。

我正在使用类型化的 HttpClient 并尝试使用 Polly 来实现重试逻辑: https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory#using-polly-with-ihttpclientfactory

当后端服务工作时,一切似乎都很好,但不幸的是,每当我的后端返回诸如 500 内部服务器错误之类的错误时,我都会收到以下异常:

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request.

System.Net.Http.HttpRequestException: An error occurred while sending the request.
 ---> System.InvalidOperationException: The stream was already consumed. It cannot be read again.
   at System.Net.Http.StreamContent.PrepareContent()
   at System.Net.Http.StreamContent.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
   at System.Net.Http.HttpContent.CopyToAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnection.SendRequestContentAsync(HttpRequestMessage request, HttpContentWriteStream stream, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   --- End of …
Run Code Online (Sandbox Code Playgroud)

c# polly asp.net-core

3
推荐指数
1
解决办法
8319
查看次数

标签 统计

c# ×3

.net ×2

dotnet-httpclient ×2

asp.net-core ×1

async-await ×1

func ×1

polly ×1