WebApi上的HttpClient非常慢 [英] HttpClient on WebApi is extremely slow

查看:133
本文介绍了WebApi上的HttpClient非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET WebApi(ApiController)为我的应用程序实现代理,并使用HttpClient通过我的授权标头发出请求.它工作正常,但是非常慢.下面是主要代码,然后是Global初始化(带有DefaultConnectionLimit)和与web.config相关的部分.

I'm implementing a Proxy for my application using ASP.NET WebApi (ApiController) and using HttpClient to make the request with my authorization header. It works fine, but it's extremely slow. Below is the main code, then the Global initialization (with DefaultConnectionLimit) and web.config related piece.

如您所见,我已经在使用静态/共享的HttpClient对象,该对象没有代理,并且对实际请求没有 HttpCompletionOption.ResponseHeadersRead .并行调用此WebApi端点,可以正常工作.

As you can see, I'm already using a static/shared HttpClient object with no Proxy and HttpCompletionOption.ResponseHeadersRead on the actual request. This WebApi endpoint is called in parallel, which works fine.

整个代码运行得足够快,但是当我使用ResponseHeadersRead async时,将返回HttpRequestMessage,其余部分直接下载并流式传输到客户端/调用者.

The entire code runs fast enough, but as I'm using ResponseHeadersRead async, the HttpRequestMessage is returned and the rest of the body is downloaded and streamed directly to the client/caller.

这是显示问题的视频.

public class ProxyController : ApiController
{
  private const string BASE_URL = "https://developer.api.autodesk.com";
  private const string PROXY_ROUTE = "api/viewerproxy/";


  // HttpClient has been designed to be re-used for multiple calls. Even across multiple threads. 
  // https://stackoverflow.com/questions/22560971/what-is-the-overhead-of-creating-a-new-httpclient-per-call-in-a-webapi-client
  private static HttpClient _httpClient;

  [HttpGet]
  [Route(PROXY_ROUTE + "{*.}")]
  public async Task<HttpResponseMessage> Get()
  {
    if (_httpClient == null)
    {
      _httpClient = new HttpClient(new HttpClientHandler() 
         {
            UseProxy = false,
            Proxy = null
         });
      _httpClient.BaseAddress = new Uri(BASE_URL);
    }

    string url = Request.RequestUri.AbsolutePath.Replace(PROXY_ROUTE, string.Empty);
    string absoluteUrl = url + Request.RequestUri.Query;

    try
    {
      HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, absoluteUrl);
      request.Headers.Add("Authorization", "Bearer " + AccessToken);

      HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

      return response;
    }
    catch (Exception e)
    {
      return new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
    }
  }
}

Global.asax,尽管我不认为这是连接限制的问题,因为所有请求都已处理,但是太慢了...

Global.asax, although I don't believe is a problem of connection limit as all the requests are processed, but just too slow...

public class Global : System.Web.HttpApplication
{
  protected void Application_Start(object sender, EventArgs e)
  {
    GlobalConfiguration.Configure(Config.WebApiConfig.Register);

    ServicePointManager.UseNagleAlgorithm = true;
    ServicePointManager.Expect100Continue = false;
    ServicePointManager.CheckCertificateRevocationList = true;
    ServicePointManager.DefaultConnectionLimit = int.MaxValue;
  }
}

以及Web.Config的一部分

And part of the Web.Config

 <system.web>
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime targetFramework="4.6" maxRequestLength="2097151" requestLengthDiskThreshold="16384" requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,\,?" />
  </system.web>

推荐答案

通过删除web.config的<system.diagnostics>部分来解决.看来,这导致了输出过多并减慢了所有HttpClient请求.

Solved by removing the <system.diagnostics> section of the web.config. It seems that it was causing an excess of output and slowing down all HttpClient requests.

为记录起见,这是我正在使用的代码,导致所有HttpClient.SendAsync调用缓慢.但这对于跟踪连接问题很有用:-)

For the record, this the code I was using and causing the slowness on all HttpClient.SendAsync calls. But this is useful for tracking connection problems :-)

<system.diagnostics>
  <sources>
    <source name="System.Net" tracemode="protocolonly" maxdatasize="1024">
      <listeners>
        <add name="System.Net"/>
      </listeners>
    </source>
    <source name="System.Net.Cache">
      <listeners>
        <add name="System.Net"/>
      </listeners>
    </source>
    <source name="System.Net.Http">
      <listeners>
        <add name="System.Net"/>
      </listeners>
    </source>
  </sources>
  <switches>
    <add name="System.Net" value="Verbose"/>
    <add name="System.Net.Cache" value="Verbose"/>
    <add name="System.Net.Http" value="Verbose"/>
    <add name="System.Net.Sockets" value="Verbose"/>
    <add name="System.Net.WebSockets" value="Verbose"/>
  </switches>
  <sharedListeners>
    <add name="System.Net"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="network.log"
    />
  </sharedListeners>
  <trace autoflush="true"/>
</system.diagnostics>

这篇关于WebApi上的HttpClient非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆