异步WebRequest麻烦

时间:2018-12-07 21:48:57

标签: async-await mstest webrequest

我正在尝试创建一些回归测试以对我们的API进行异步调用。无论我如何尝试,我一直都收到null引用错误。我尝试了几种不同的调用请求的方法。我机智的尽头。我可以在代码中放置一个断点来检查URL并在Postman中运行该URL,它会按预期返回数据。我传递了一些标题,但没有任何异常。

下面是堆栈跟踪和我的代码。谁能看到我想念的东西?

谢谢

<GetApiResponse>d__17`1.MoveNext() in C:\Users\foo\Documents\test.api\Common\Base.cs:line 199 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at Test.API.ResultsTest.<ResultsAPI_SortByLowToHigh>d__1.MoveNext() in C:\Users\voo\Documents\test.api\ResultsTest.cs:line 74 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() Result Message: Test method Test.API.ResultsAPI_SortByLowToHigh threw exception: System.NullReferenceException: Object reference not set to an instance of an object.

try
{
    var webRequest = WebRequest.Create(url);
    webRequest.Method = "GET";
    webRequest.ContentType = "application/json";
    webRequest.Headers.Add("ApiVersion", "1");
    webRequest.Headers.Add("Country-Code", "US");
    webRequest.Headers.Add("Currency-Code", "USD");

    Task<WebResponse> responseTask = webRequest.GetResponseAsync();

    using (var webResponse = await responseTask)
    {
        using (var sres = webResponse.GetResponseStream())
        {
            var ms = new MemoryStream();
            if (sres != null) await sres.CopyToAsync((ms));
            ms.Position = 0;
            using (var sr = new StreamReader(ms))
            {
                JsonResponse = sr.ReadToEnd();
            }
        }
    }

    if (!string.IsNullOrEmpty(JsonResponse))
    {
        response = JsonConvert.DeserializeObject<ServiceResponse>(JsonResponse);
    }
    else
    {
        throw new Exception(typeof(ServiceResponse).Name + " API returned null Response");
    }
    return response;
}
catch (WebException e)
{
    ErrorMsg.AppendLine(e.Message);
    throw;
}

0 个答案:

没有答案