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

拜拜、爱过 提交于 2019-12-10 02:56:24

问题


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;
}

回答1:


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());
}


来源:https://stackoverflow.com/questions/25047311/the-request-message-was-already-sent-cannot-send-the-same-request-message-multi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!