【发布时间】:2017-05-08 23:40:54
【问题描述】:
异步执行 REST 调用和处理响应。
System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Net.Http.Headers.HttpHeaders.AddHeaderToStore(String name, HeaderStoreItemInfo info)
at System.Net.Http.Headers.HttpHeaders.CreateAndAddHeaderToStore(String name)
at System.Net.Http.Headers.HttpHeaders.GetOrCreateHeaderInfo(String name, Boolean parseRawValues)
at System.Net.Http.Headers.HttpHeaders.SetParsedValue(String name, Object value)
at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
at System.Net.Http.HttpClientHandler.PrepareAndStartContentUpload(RequestState state)
--- 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()
System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- 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()
代码:
var resultTask = base.WrapCallWithLogging(requestUri, task, method, sw, content);
resultTask.ContinueWith(t =>
{
// Do something
GetMessage(); //access the variable content
};
return resultTask;
我的理解是我们得到了这个异常,因为出于某种原因,标题被创建了两次。这可能是异步任务的问题。谁能指出正确的文档?
base.WrapCallWithLogging()方法:
protected virtual Task<HttpResponseMessage> WrapCallWithLogging(RestUri requestUri, Task<HttpResponseMessage> task, HttpMethod method, Stopwatch sw, HttpContent content = null)
{
var uriTemplate = requestUri.BuildFullTemplateString();
Logger.DebugFormat("Making http '{0}' call to '{1}'", method, uriTemplate);
return task.ContinueWith(r =>
{
var result = r.Result;
sw.Stop();
Logger.DebugFormat("Ending http '{0}' call to '{1}' with status code {2} in {3} ms",
method,
uriTemplate.ToString(),
result == null ? HttpStatusCode.InternalServerError : result.StatusCode,
sw.ElapsedMilliseconds);
return result;
});
}
【问题讨论】:
-
WrapCallWithLogging()显然有一些问题。显示它的代码。 -
abatishchev 添加了基本方法
-
嗯,有趣/奇怪。您是否在任何地方手动操作 http 客户端的标头?
-
你在使用 RestSharp 吗?能更新到最新吗?您可以尝试使用内置的 HttpClient 代替吗?
-
这不是一个解决方案,但也尝试使用
async/await而不是普通的TPLContinueWith()