【发布时间】:2013-10-08 23:03:07
【问题描述】:
我正在构建一个给定 HttpContent 对象的函数,它将发出请求并在失败时重试。但是,我收到异常说 HttpContent 对象在发出请求后被释放。无论如何要复制或复制 HttpContent 对象,以便我可以发出多个请求。
public HttpResponseMessage ExecuteWithRetry(string url, HttpContent content)
{
HttpResponseMessage result = null;
bool success = false;
do
{
using (var client = new HttpClient())
{
result = client.PostAsync(url, content).Result;
success = result.IsSuccessStatusCode;
}
}
while (!success);
return result;
}
// Works with no exception if first request is successful
ExecuteWithRetry("http://www.requestb.in/xfxcva" /*valid url*/, new StringContent("Hello World"));
// Throws if request has to be retried ...
ExecuteWithRetry("http://www.requestb.in/badurl" /*invalid url*/, new StringContent("Hello World"));
(显然我不会无限期地尝试,但上面的代码基本上就是我想要的)。
它会产生这个异常
System.AggregateException: One or more errors occurred. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.StringContent'.
at System.Net.Http.HttpContent.CheckDisposed()
at System.Net.Http.HttpContent.CopyToAsync(Stream stream, TransportContext context)
at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Submission#8.ExecuteWithRetry(String url, HttpContent content)
是否有复制 HttpContent 对象或重用它的方法?
【问题讨论】:
-
其他答案很好实现重试。但这里真正的问题是因为您的 HttpContent 在您的帖子之后被处置。您需要在每次重试之前重新创建 StringContent。你不会有这样的 ObjectDisposedException
-
没错,这里的异常是由于每次发帖后HttpClient都会处理HttpContent造成的。为每个 Polly 执行克隆 HttpContent 是解决方案。可以在here 找到一些可用的克隆扩展。
标签: c# dotnet-httpclient httpcontent