我正在使用ASP.NET WebApi(ApiController)来实现我的应用程序的代理,并使用HttpClient在请求中加入授权头。虽然它可以运行,但速度非常慢。下面是主要代码、全局初始化(包括DefaultConnectionLimit)和web.config相关部分。
正如您所看到的,我已经在实际请求中使用了静态/共享HttpClient对象,没有代理,并且在请求中使用了HttpCompletionOption.ResponseHeadersRead。这个WebApi端点被并行调用,可以正常工作。
整个代码运行速度足够快,但由于我使用了ResponseHeadersRead异步方式,因此HttpRequestMessage被返回后,其余部分仍需下载并直接流式传输到客户端/调用方。
以下是一个视频展示问题:链接。
正如您所看到的,我已经在实际请求中使用了静态/共享HttpClient对象,没有代理,并且在请求中使用了HttpCompletionOption.ResponseHeadersRead。这个WebApi端点被并行调用,可以正常工作。
整个代码运行速度足够快,但由于我使用了ResponseHeadersRead异步方式,因此HttpRequestMessage被返回后,其余部分仍需下载并直接流式传输到客户端/调用方。
以下是一个视频展示问题:链接。
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://dev59.com/xGEh5IYBdhLWcg3wTB_2
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="<,>,*,%,&,\,?" />
</system.web>
HttpCompletionOption.ResponseHeadersRead
),会怎样呢?它是单个请求慢还是在负载下慢? - Andrii Litvinov