我正在使用 ASP.NET WebApi (ApiController) 为我的应用程序实现代理,并使用 HttpClient 通过我的授权标头发出请求。它工作得很好,但速度非常慢。下面是主要代码,然后是全局初始化(使用DefaultConnectionLimit)和web.config相关部分。
如您所见,我已经在使用没有代理的静态/共享 HttpClient 对象,并且HttpCompletionOption.ResponseHeadersRead根据实际要求。该 WebApi 端点被并行调用,工作正常。
整个代码运行得足够快,但是当我使用 ResponseHeadersRead 异步时,会返回 HttpRequestMessage,并且正文的其余部分会被下载并直接流式传输到客户端/调用者。
Here is 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);
}
}
}
Global.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>