最近在使用.net core 2.1 httpclient时遇到一个问题,看了一天,实在搞不定,特来请教各路大神:
我是调用Azure的Application Insights REST API来获取我们系统的接口调用情况。
我的调用代码如下:
public class AzureApiClient
{
private readonly HttpClient _httpClient;
public AzureApiClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetQuery(string querystring)
{
Trace.TraceInformation("基础路径:" + _httpClient.BaseAddress.ToString());
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.DefaultRequestHeaders.Add("x-api-key", Account.ApiKey);
var response = await _httpClient.GetAsync($"/v1/apps/appid/query?query={querystring}");
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
else
{
return response.ReasonPhrase;
}
}
}
public class ApiLogController{
private readonly AzureApiClient _apiClient;
public ApiLogController(AzureApiClient apiClient)
{
_apiClient = apiClient;
}
[HttpGet]
[ProducesResponseType(200)]
public async Task<IActionResult> GetApiCallDetails(){
string querystring = "traces| sort by timestamp desc "
_apiClient.GetQuery(querystring)
// 其他代码
}
}
当第一次调用时,很快响应成功了,返回了正确的数据,但是同样的条件间隔几秒之后,再次调用则响应失败。报错:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond。
第一次调用成功之后,间隔的足够久或者重启系统,可以再次成功调用。
一开始我以为是Azure的Application Insights REST API设定问题,不允许短时间内再次调用,但是我用postman测试该url是可以短时间内多次调用的,后来我就怀疑我的代码问题,然后我单元测试上面的方法,如下:
[Fact]
public async void TestGetQuery(){
string querystring="trace | sort by timestamp desc";
GetQuery(querystring)
}
这样单元测试,是可以多次启动调用的,然后我想,我多次启动单元测试其实相当于我的系统多次重启,这种情况其实判断不了代码是否有问题。于是,我把单元测试代码修改成如下:
[Fact]
public async void TestGetQuery(){
string querystring="trace | sort by timestamp desc";
for(int i = 0; i < 3; i++){
GetQuery(querystring)
Thread.Sleep(2000);
}
}
两秒内重复请求,报了和上面一样的错误:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond。
总感觉,这个报错大意就是httpclient无法建立连接了,我是纳闷,才请求一个难道就耗尽资源了?
贴一下这几个类型是怎么依赖注入的。
感觉是生命周期有问题。