【问题标题】:C# HttpClient doesnt resolve host when used from Web Api project从 Web Api 项目中使用 C# HttpClient 时不解析主机
【发布时间】:2017-11-10 12:26:15
【问题描述】:

问题

在 WebApi 控制器中,我尝试使用 HttpClient 向另一个网站发出 http 请求 - 但它总是失败,并说主机没有响应,或者它未能建立连接。

如何重现:

在 Visual Studio (Enterprise on this end) 2017 中,使用 Azure Web Api 模板创建一个新项目(文件 -> 新建 -> 项目 -> ASP.NET Web 应用程序 (.NET Framework) -> 确定 -> Azure网络接口。

确保选择 .NET Framework 4.7.1。 (除了.net core,我没有用其他框架测试过)

在 ValuesController 中,从 Get 方法调用任何 URL 并尝试使用 Result StatusCode 进行响应。

代码:

public class ValuesController : ApiController
{
    // GET api/values
    [SwaggerOperation("GetAll")]
    public IEnumerable<string> Get()
    {
        using (var client = new HttpClient())
        {
            var result = client.GetAsync("https://www.google.com").Result;
            return new string[] { result.StatusCode.ToString(), "value2" };
        }
    }
}

调试:

  • 我创建了一个单独的控制台应用程序,并在那里做了同样的事情。 [作品]
  • 我创建了一个单独的 .net core web api 项目,并在那里做了同样的事情。 [作品]

我围绕这个错误进行了相当多的搜索,但最终没有结果。

有什么建议吗?

异常详情:

System.AggregateException occurred
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=<Cannot evaluate the exception source>
  StackTrace:
   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 WebApplication2.Controllers.ValuesController.Get() in C:\Users\<user>\documents\visual studio 2017\Projects\WebApplication2\WebApplication2\Controllers\ValuesController.cs:line 19
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

Inner Exception 1:
HttpRequestException: An error occurred while sending the request.

Inner Exception 2:
WebException: Unable to connect to the remote server

Inner Exception 3:
SocketException: 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 216.58.209.99:443

【问题讨论】:

  • 确切和完整的例外是什么?你为什么用.Result 阻止异步调用?
  • 只是我测试了不同方式的结果,并且编辑到这里。使其异步不会改变结果。附加到原始帖子的例外:)
  • 当我尝试访问该 IP 地址时,该站点出现问题。它会在后台尝试一些失败的 xhr 调用。我无法解释为什么它适用于您的其他项目类型。如果您遇到像 SpaceX 这样的真正的、仅限 json 的服务怎么办? api.spacexdata.com/v1/launches
  • 如果您考虑出现在异常中的 IP,该站点是 www.google.no!异常只显示解释的地址。
  • 您可能想阅读Don't Block on Async Code - 您对Result 的使用是潜在死锁的典型示例。

标签: c# .net asp.net-web-api dotnet-httpclient


【解决方案1】:

问题已解决 - 解决方案:

我在代理之后,似乎 IIS Express 或 .net Framework 中的某些东西,不会像 .net Core 那样自动获取系统中定义的代理设置,以及控制台应用程序。

使用代理地址将代理地址添加到web.config 就可以了。

<system.net>
    <defaultProxy>
      <proxy usesystemdefault="True" proxyaddress="http://www-proxy.somedomain.com:80" bypassonlocal="False"/>
      <bypasslist>
        <add address="[a-z]+\.somedomain\.com$"/>
        <add address="[a-z]+\.somedomain\.net$"/>
      </bypasslist>
    </defaultProxy>
  </system.net>

希望这可以帮助其他遇到此问题的人!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2015-11-01
    • 1970-01-01
    • 2014-06-18
    • 2011-01-10
    • 2020-02-13
    • 2011-09-01
    相关资源
    最近更新 更多