最近博客园被**了, 赶紧水一文支持一下博客园,加油!
当HttpClient被使用过之后, 在修改它们的属性会抛出错误This instance has already started one or more requests. Properties can only be modified before sending the first request.
HttpClient 对象, 我们要修改它的 TimeoutHttpClient, 我们要修改它的 Timeout可以把 HttpClient 的生命周期改成 Transient, 并且每次要用的时候都从 IServiceProvider 获取.
在注册 的时候把它的 修改为
services.AddHttpClient<MyApiService>((sp, client) =>
{
client.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
client.BaseAddress = sp.GetService<MyOptions>().ApiEndpoint;
}
});然后调用的地方使用自己的来实现即可, 其实在内部也是一样的方式.
HttpClient.SendAsync的部分源代码:CancellationTokenSource cts;
bool disposeCts;
bool hasTimeout = _timeout != s_infiniteTimeout;
if (hasTimeout || cancellationToken.CanBeCanceled)
{
disposeCts = true;
cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _pendingRequestsCts.Token);
if (hasTimeout)
{
cts.CancelAfter(_timeout);
}
}
else
{
disposeCts = false;
cts = _pendingRequestsCts;
}