Is there anything wrong with my code here? I keep getting this error:
System.InvalidOperationException: The request message was already sent. Cannot send the same request message multiple times.
My HttpRequestMessage is inside a Func so I figured I get a brand new request each time I pass in 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;
}
You are calling the same func
parameter twice:
var response = await ProcessRequestAsync(func);
//...
response = await ProcessRequestAsync(func);
In this case func
returns the same request every single time. It doesn't generate a new one every time you call it. If you truly need a different request each time then func
needs to return a new message each call:
var response = await GetAsync(() => new HttpRequestMessage()); // Create a real request.
public async Task<HttpResponseMessage> GetAsync(Func<HttpRequestMessage> requestGenerator)
{
return await RequestAsync(() => requestGenerator());
}
I had the same issue, but no repetition in my code. Turned out I had added a watch on an asynchronous process. That watch called the process while I stepped through the code, so that when I got to the line I was trying to debug it crashed with this error message. Removing all watches solved the problem. Leaving this here for other people who might have the same problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With