.NET HttpClient sendAsync() 第二次请求超时

.NET HttpClient sendAsync() Timeout on second request specifically

我一直在 ASP.NET 上开发类似代理的控制器,它从传入请求中获取 URL 并使用 HttpClient 调用 URL,然后 return文件。

这个类似代理的控制器是这样工作的:


(这4个请求几乎同时发送到controller)

请忽略POST情况

控制器

public async Task<FileStreamResult> Proxy(string method, string url, string data = "")
{
    myHttpClient client = new myHttpClient();
    Tuple<MemoryStream,string> result = await client.Proxy(this.Request, method, url).ConfigureAwait(false);
    return File(result.Item1,result.Item2); //file stream and file type
}

HttpClient

public class myHttpClient
{
    private static HttpClient _httpClient;
    static myHttpClient()
    {
        if (_httpClient == null) {
            _httpClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
            _httpClient.Timeout = TimeSpan.FromSeconds(7);
            Log ocLog = new Log();
            ocLog.Write("init client " + ServicePointManager.DefaultConnectionLimit ,false);
        }
    }
    public async Task<Tuple<MemoryStream, string>> Proxy(HttpRequestBase contextRequest, string method, string url)
    {
        var request = new HttpRequestMessage();
        request.RequestUri = new Uri("http://localhost" + url);
        if (method == "GET")
        {
            request.Method = HttpMethod.Get;
            request.Content = null;
        }
        else if (method == "POST")
        {
            request.Method = HttpMethod.Post;
        }

        //copy request header from context.Request
        foreach (string headerName in contextRequest.Headers)
        {
            string[] headerValues = contextRequest.Headers.GetValues(headerName);
            if (!request.Headers.TryAddWithoutValidation(headerName, headerValues))
            {
                request.Content.Headers.TryAddWithoutValidation(headerName, headerValues);
            }
        }

        try
        {
            using (HttpResponseMessage response = await _httpClient.SendAsync(request).ConfigureAwait(false))
            {
                if (response.IsSuccessStatusCode)
                {
                    var contentBytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                    MemoryStream ms = new MemoryStream(contentBytes);
                    return new Tuple<MemoryStream, string>(ms, response.Content.Headers.ContentType.ToString());
                }
                else
                {
                    return null;
                }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

我尝试了什么

  1. 正在检查ServicePointManager.DefaultConnectionLimit。很大。
  2. 用System.net.WebRequest库代替HttpClient,还是一样

问题已通过将应用程序池的 "Maximum Process Workers" 设置为 3 来解决。它成功了