首页 > 解决方案 > 部署时的 HttpClient 性能问题

问题描述

我有下面的代码。在本地运行它,我会在不到 1 秒的时间内从 API 获得响应。

当我将它部署到服务器时,需要 3 到 10 分钟才能得到响应!

我已经部署到 3 个不同的服务器,结果相同。知道可能出了什么问题吗?

下面是我的代码:

string response = string.Empty;
try
{
    var content = new StringContent(JsonConvert.SerializeObject(request), System.Text.Encoding.UTF8, "application/json");

    using (var client = new HttpClient())
    {
        var responseMessage = client.PostAsync("https://myapi/createshorturl", content).Result;
        response = responseMessage.Content.ReadAsStringAsync().Result;
        return JsonConvert.DeserializeObject<CreateShortUrlResponse>(response);
    }
}
catch (Exception x)
{
    return null;
}

标签: c#.netdotnet-httpclient

解决方案


很可能您使用 HttpClient 错误。在继续使用之前先看看以下文章:

TL;博士:

  • HttpClient 持有底层套接字的时间比你想象的要长得多。
  • 重用 HttpClient,不要为每个请求创建一个新的。
  • 使用 IHttpClientFactory
  • .Result

推荐阅读