请求消息已发送。 无法多次发送相同的请求消息
我的代码在这里有什么问题吗? 我一直收到这个错误:
System.InvalidOperationException:请求消息已发送。 无法多次发送相同的请求消息。
我的HttpRequestMessage在Func中,所以我想每次传入func()时都会得到一个全新的请求。
public async Task GetAsync(HttpRequestMessage request) { return await RequestAsync(() => request); } public async Task RequestAsync(Func func) { var response = await ProcessRequestAsync(func); if (response.StatusCode == HttpStatusCode.Unauthorized) { WaitForSomeTime(); response = await ProcessRequestAsync(func); } return response; } private async Task ProcessRequestAsync(Func 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 GetAsync(Func requestGenerator) { return await RequestAsync(() => requestGenerator()); }