我已经使用HttpClient调用API,但给我一个错误,例如“此实例已经启动了一个或多个请求。只能在发送第一个请求之前修改属性。”
下面是我的代码
public async Task<Result<T>> Get<T>(Token token, string route)
{
var result = new Result<T>();
try
{
_httpClient.Timeout = new TimeSpan(0, 0, GlobalLogic.SessionTimeOut);
var response = await _httpClient.GetAsync(GlobalConstant.ApiUrl + route, token);
token.ThrowIfCancellationRequested();
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
result.Data = JsonConvert.DeserializeObject<T>(content);
}
else
{
Error error = new Error();
error.error_description = content;
error.Code = (int)response.StatusCode;
if (response.StatusCode==System.Net.HttpStatusCode.Unauthorized)
{
error.Code = (int)System.Net.HttpStatusCode.Unauthorized;
}
result.error = error;
}
}
catch (Exception ex)
{
var message = ex.Message;
}
return result;
}
我发现此解决方案使用不使用本地HTTP客户端对象或每次创建一个全局HTTP客户端对象。
创建HttpClient的本地对象,并在您的类或构造函数中使用它。
public HttpClient _httpClient = new HttpClient { BaseAddress = new Uri(ApiUrl) };;