2

当使用推荐的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}");
    }
}

退货

OK - Timeout: 100000
4

1 回答 1

6

这是因为您需要创建一个HttpClient与您配置的名称相同的名称,即"PushNotification".

return new OkObjectResult($"OK - Timeout: {this.HttpClientFactory.CreateClient("PushNotification").Timeout.TotalMilliseconds}");
于 2019-08-07T16:49:57.073 回答