【问题标题】:c# HttpClient just stops without any indication whyc# HttpClient 只是停止,没有任何迹象表明为什么
【发布时间】:2018-11-05 16:46:05
【问题描述】:

我正在尝试从我们的 API 实例中获取数据。我拥有的代码几乎是复制的 MS 网站,其中包含在 SO 上找到的柚木。我正在使用的代码是这样的:

string peopleEndpoint = $"{apiConf.ApiEndpoint}/{apiConf.dbspec}/_table/mdm.PEOPLE_SV";
string json = null;
try
{
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Add("X-Api-Key", apiConf.ApiKey);
        HttpResponseMessage response = await httpClient.GetAsync(peopleEndpoint);
        json = await response.Content.ReadAsStringAsync();
    }
}
catch (Exception ex)
{
    Debug.WriteLine(ex.ToString());
    throw;
}

配置值很好...我可以将它们复制并粘贴到 cURL 命令中并获取数据。与标题相同。

现在当我调试时,执行此行后执行停止:

HttpResponseMessage response = await httpClient.GetAsync(peopleEndpoint);

而且,在输出窗口中,我看到的是:

The program '[10172] dotnet.exe' has exited with code 0 (0x0).
The program '[10172] dotnet.exe: Program Trace' has exited with code 0 (0x0).

如何找出导致此故障的原因?

框架标注为:

<TargetFramework>netcoreapp2.1</TargetFramework>

【问题讨论】:

  • 当您使用调试器运行它时会发生什么?什么平台?
  • 我正在开发这个应用程序,所以它正在调试中运行。它在带有 Win Server 2016 Standard 的 VM 上运行。主机操作系统是 Mac。
  • 使用调试器运行它,而不仅仅是在调试模式下。
  • 代码是一直异步到顶部,还是有一个非异步方法在某处调用此代码,可能不会等到它完成。这就是我闻起来的味道。
  • 与您的问题并不真正相关,但您不应该在 using 语句中使用 HttpClient 。由于您使用的是 .NET Core 2.1,因此您可以使用新的 HttpClientFactory:docs.microsoft.com/en-us/aspnet/core/fundamentals/…

标签: c# .net-core dotnet-httpclient


【解决方案1】:

代码是一直异步到顶部,还是有一个非异步方法在某处调用此代码,可能不会等到它完成。这就是我闻起来的味道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 2014-08-02
    • 2018-01-11
    • 1970-01-01
    • 2019-12-14
    • 2016-02-14
    • 1970-01-01
    相关资源
    最近更新 更多