连接到API时出错但在C#中运行单元测试时能够连接

时间:2017-11-29 19:17:59

标签: c# .net api

我正在尝试构建一个使用HttpClient类从Web API连接的服务。该服务在单元测试下运行正常但在从控制器调用服务时遇到错误。这是我服务的代码

public List<Recipe> FindRecipe(string searchTerm)
{
    List<Recipe> result = null;
    string apiPath = BuiltApiPath(searchTerm);
    var task = AppHttpClient.Instance().
        GetAsync(new Uri(apiPath))
        .ContinueWith((taskReponse) =>
        {
            var response = taskReponse.Result;
            var jsonString = response.Content.ReadAsStringAsync();
            jsonString.Wait();
            dynamic data = JsonConvert.DeserializeObject<dynamic>(jsonString.Result);
            result = ((IEnumerable)data.hits).Cast<dynamic>().
                Select(h => new Recipe { Name = h.recipe.label, ImageUrl = h.recipe.image, Uri = h.recipe.uri }).
                ToList();
        });
    task.Wait();
    return result;
}

这是我的例外

Exception information: 
    Exception type: AggregateException 
    Exception message: One or more errors occurred.
   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 RecipeFinder.Services.RecipeService.<>c__DisplayClass0_0.<FindRecipe>b__0(Task`1 taskReponse) in \\dtchyb-mnmh001\c_wfp_users\u595357\my documents\visual studio 2015\Projects\RecipeFinder\RecipeFinder\Services\RecipeService.cs:line 24
   at System.Threading.Tasks.ContinuationTaskFromResultTask`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

An error occurred while sending the request.

Unable to connect to the remote server
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 107.20.173.119:443
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

0 个答案:

没有答案