Reputation: 45333
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
Upvotes: 7
Views: 15532
Reputation: 4307
For me we just use the connection for one api client, so we just register it like this:
services.AddHttpClient<IMyApiClient, MyApiClient>(httpClient =>
{
httpClient.BaseAddress = new Uri(hostContext.Configuration.GetValue<string>("MyApiUrl"));
httpClient.Timeout = TimeSpan.FromSeconds(hostContext.Configuration.GetValue<int>("MyApiTimeoutSeconds"));
});
Upvotes: 0
Reputation: 45333
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}");
Upvotes: 11