等待使用httpClient.GetAsync(url)并获取错误System.NullReferenceException未处理

时间:2013-02-19 14:46:42

标签: c# async-await httpclient

我正在使用VS 2012并设置目标framework 4.0.

public async Task<HttpResponseMessage> GetResponse(Uri url)             
{                 
    this.httpClient.DefaultRequestHeaders.Accept.Clear();                 
    HttpResponseMessage response = await this.httpClient.GetAsync(url);                 
    response.EnsureSuccessStatusCode();             
}

错误:

System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Microsoft.CompilerServices.AsyncTargetingPack.Net4
StackTrace:
Server stack trace: at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean  setImpersonationContext) at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext) at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state) at System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state) at System.Web.LegacyAspNetSynchronizationContext.Post(SendOrPostCallback callback, Object state) at System.Runtime.CompilerServices.TaskAwaiter.<>c__DisplayClassa.<OnCompletedInternal>b__0(Task param0)
        Exception rethrown at [0]: at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__1(Object state)
           at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
           at System.Threading.ThreadPoolWorkQueue.Dispatch()
           at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
      InnerException: 
    -------------------------------------------------

我已经从"Microsoft.CompilerServices.AsyncTargetingPack安装了NuGet“,但仍然收到此错误。有任何建议。

0 个答案:

没有答案