我这里的代码有什么问题吗?我不断收到此错误:
System.InvalidOperationException: The request message was already sent. Cannot send the same request message multiple times.
我的 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;
}
最佳答案
您正在两次调用相同的 func
参数:
var response = await ProcessRequestAsync(func);
//...
response = await ProcessRequestAsync(func);
在这种情况下,func
每次都返回相同的请求。它不会在您每次调用时生成一个新的。如果你真的每次都需要不同的请求,那么 func
需要在每次调用时返回一条新消息:
var response = await GetAsync(() => new HttpRequestMessage()); // Create a real request.
public async Task<HttpResponseMessage> GetAsync(Func<HttpRequestMessage> requestGenerator)
{
return await RequestAsync(() => requestGenerator());
}
关于c# - 请求消息已发送。不能多次发送同一个请求报文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25047311/