Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The request message was already sent. Cannot send the same request message multiple times

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;
}
like image 972
Prabhu Avatar asked Jul 30 '14 21:07

Prabhu


2 Answers

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());
}
like image 108
i3arnon Avatar answered Nov 04 '22 15:11

i3arnon


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.

like image 41
Lavandysh Avatar answered Nov 04 '22 15:11

Lavandysh