asp.net WebApi上的HttpClient速度极慢

fcg9iug3  于 2022-12-15  发布在  .NET
关注(0)|答案(2)|浏览(288)

我正在使用ASP.NET WebApi(ApiController)为我的应用程序实现一个代理服务器,并使用HttpClient用我的授权头发出请求。它工作正常,但速度非常慢。下面是主要代码,然后是全局初始化(带有DefaultConnectionLimit)和web.config相关的部分。
正如您所看到的,我已经在实际请求中使用了一个静态/共享的HttpClient对象,没有Proxy和HttpCompletionOption.ResponseHeadersRead
整个代码运行得足够快,但是当我使用ResponseHeadersRead异步时,HttpRequestMessage被返回,正文的其余部分被下载并直接流传输到客户机/调用者。
a video显示了这个问题。

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);
    }
  }
}

asax,虽然我不相信是一个连接限制的问题,因为所有的请求都处理,但只是太慢了...

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的一部分

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

hl0ma9xz1#

通过删除web. config的<system.diagnostics>部分解决。看起来它导致了输出过多,并降低了所有HttpClient请求的速度。
声明一下,这是我使用的代码,导致所有HttpClient.SendAsync调用变慢。但这对跟踪连接问题很有用:-)

<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>
w41d8nur

w41d8nur2#

5年后,我遇到了同样的问题。我通过删除VS项目属性设置中的所有 Analyzers 来解决这个问题:

相关问题