C#中使用HttpClient竟然遭遇超时,报错如下:

The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing

我们只要加长它的超时时间就可以了,我的使用场景是下载一个大文件时会遇到,

public class ReporterAccessLayer
{
   
    private readonly HttpClient _httpClient;
    private readonly IHttpClientFactory _httpFactory;
    private readonly JsonSerializerOptions _options;

    public ReporterAccessLayer(IHttpClientFactory httpFactory)
    {
        _httpFactory =httpFactory;
        _options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
    }

    public async Task<List<Reports>> GetAll()
    {
      try
      {
         HttpClient  httpClient=_httpFactory.CreateClient();
          httpClient.Timeout = TimeSpan.FromMinutes(10);
         return await httpClient.GetAsync<List<Reports>>("/ReportsPage/GatherAllReports");
      }
      catch
      {
         // do exception handling

      } 
    }

}

例如在这里我设计的超时时间为10分钟,下载一个200M的文件足够了。