HttpClient.Timeout AddHttpClient 配置被忽略
HttpClient.Timeout configured by AddHttpClient is ignored
当使用推荐的 AddHttpClient
扩展来配置 IHttpClientFactory
并包含一些默认 HttpClient
设置时,我为 Timeout
属性 设置的值在我随后创建的 HttpClient
个实例中没有看到。
Demo 使用 Azure Function,类似于 ASP.NET Core.
public class Startup : FunctionsStartup
{
public static readonly int PushTimeoutMs = 3000;
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient("PushNotification", client =>
{
client.Timeout = TimeSpan.FromMilliseconds(PushTimeoutMs);
});
}
}
正在创建客户端。
public class TestFunctionTwo
{
public TestFunctionTwo(IHttpClientFactory httpClientFactory)
{
this.HttpClientFactory = httpClientFactory;
}
//
public IHttpClientFactory HttpClientFactory { get; }
//
[FunctionName("TestFunctionTwo")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
await Task.Delay(100);
return new OkObjectResult($"OK - Timeout: {this.HttpClientFactory.CreateClient().Timeout.TotalMilliseconds}");
}
}
Returns
OK - Timeout: 100000
这是因为您需要创建一个与您配置的同名的 HttpClient
,即 "PushNotification"
。
return new OkObjectResult($"OK - Timeout: {this.HttpClientFactory.CreateClient("PushNotification").Timeout.TotalMilliseconds}");
当使用推荐的 AddHttpClient
扩展来配置 IHttpClientFactory
并包含一些默认 HttpClient
设置时,我为 Timeout
属性 设置的值在我随后创建的 HttpClient
个实例中没有看到。
Demo 使用 Azure Function,类似于 ASP.NET Core.
public class Startup : FunctionsStartup
{
public static readonly int PushTimeoutMs = 3000;
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient("PushNotification", client =>
{
client.Timeout = TimeSpan.FromMilliseconds(PushTimeoutMs);
});
}
}
正在创建客户端。
public class TestFunctionTwo
{
public TestFunctionTwo(IHttpClientFactory httpClientFactory)
{
this.HttpClientFactory = httpClientFactory;
}
//
public IHttpClientFactory HttpClientFactory { get; }
//
[FunctionName("TestFunctionTwo")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
await Task.Delay(100);
return new OkObjectResult($"OK - Timeout: {this.HttpClientFactory.CreateClient().Timeout.TotalMilliseconds}");
}
}
Returns
OK - Timeout: 100000
这是因为您需要创建一个与您配置的同名的 HttpClient
,即 "PushNotification"
。
return new OkObjectResult($"OK - Timeout: {this.HttpClientFactory.CreateClient("PushNotification").Timeout.TotalMilliseconds}");