AddHttpClient配置的HttpClient.Timeout被忽略

时间:2019-08-07 16:49:57

标签: .net-core httpclientfactory

使用推荐的AddHttpClient扩展名配置IHttpClientFactory并包括一些默认的HttpClient设置时,我在Timeout属性中设置的值在{我随后创建的{1}}个实例。

演示使用Azure函数,就像ASP.NET Core。

HttpClient

创建客户端。

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}");
    }
}

1 个答案:

答案 0 :(得分:2)

这是因为您需要创建一个与您配置的名称相同的OK - Timeout: 100000 ,即HttpClient

"PushNotification"