等待PostAsJsonAsync时抛出AggregateException

nik*_*owj 11 c# asp.net task-parallel-library asp.net-web-api

在等待API帖子完成我如何解决这个问题时,AggregateException正在抛出?

我的API调用类似于此

using (var httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri(workflowUrl);
    var task = httpClient.PostAsJsonAsync("api/apiname/execute/", executeModel)
                             .ContinueWith(x => x.Result.Content.ReadAsAsync<bool>().Result);

    Task continuation = task.ContinueWith(x =>
    {
        bool response = x.Result;
    });
    continuation.Wait(); 

}
Run Code Online (Sandbox Code Playgroud)

在等待POST完成时,我得到了Exception.

  System.AggregateException was caught
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
       at System.Threading.Tasks.Task.Wait()
       at 
  InnerException: System.AggregateException
       Message=One or more errors occurred.
       Source=mscorlib
       StackTrace:
            at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
            at System.Threading.Tasks.Task`1.get_Result()
            at 
            at System.Threading.Tasks.Task`1.<>c__DisplayClass17.<ContinueWith>b__16(Object obj)
            at System.Threading.Tasks.Task.InnerInvoke()
            at System.Threading.Tasks.Task.Execute()
       InnerException: System.AggregateException
            Message=One or more errors occurred.
            Source=mscorlib
            StackTrace:
                 at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
                 at System.Threading.Tasks.Task`1.get_Result()
                 at WebUI.ListController.<ListRepeater_ItemCommand>b__f(Task`1 x) in PostAsJsonAsync:line 741
                 at System.Threading.Tasks.Task`1.<>c__DisplayClass1a`1.<ContinueWith>b__19()
                 at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
                 at System.Threading.Tasks.Task.InnerInvoke()
                 at System.Threading.Tasks.Task.Execute()
            InnerException: System.Threading.Tasks.TaskCanceledException
                 Message=A task was canceled.
                 InnerException:
Run Code Online (Sandbox Code Playgroud)

Tom*_*uλa 17

你发布了一大块数据吗?一旦我有类似的问题.我认为潜在的问题是由于带宽问题偶尔会出现超时.我尝试获取任务并手动等待它然后检查.IsFaulted,.IsCancelled.Result抛出AggregateException/ TaskCancelledException.

也许你应该尝试增加默认为100秒的HttpClient.Timeout属性?

  • 谢谢你的提示,这让我发疯了.我不知道他们为什么不抛出更明智的东西,比如"超时过期". (6认同)