Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient.Timeout configured by AddHttpClient is ignored

When using the recommended AddHttpClient extension to configure the IHttpClientFactory and include some default HttpClient setup, the value I set for the Timeout property is not seen in the HttpClient instances that I subsequently create.

Demo uses Azure Function, which is like 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);
        });
    }
}

Creating the client.

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
like image 929
Luke Puplett Avatar asked Jul 24 '26 08:07

Luke Puplett


1 Answers

This is because you need to create an HttpClient of the same name as the one you've configured, i.e. "PushNotification".

return new OkObjectResult($"OK - Timeout: {this.HttpClientFactory.CreateClient("PushNotification").Timeout.TotalMilliseconds}");
like image 141
Luke Puplett Avatar answered Jul 26 '26 21:07

Luke Puplett