Currently, I have this configuration for http client that I can use and inject when needed, wrapped with JWT authentication to hit some API address that has multiple end points:
builder.Services.AddHttpContextAccessor();
builder.Services.AddHttpClient("ApiClient", client =>
{
client.BaseAddress = new Uri(builder.Configuration["BaseUrl:ApiUrl"]);
})
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
EnableMultipleHttp2Connections = true,
MaxConnectionsPerServer = 10,
MaxResponseHeadersLength = 64 * 1024,
});
builder.Services.AddScoped(sp =>
{
var factory = sp.GetRequiredService<IHttpClientFactory>();
var client = factory.CreateClient("ApiClient");
var httpContext = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
var jwtToken = httpContext?.User?.FindFirst("JwtToken")?.Value;
if (!string.IsNullOrEmpty(jwtToken))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
}
return client;
});
I am just wondering if this is the right way to do it and whether there are other better approaches to achieve that in case this is considered costly or inefficient. I am doing blazor server and I rely on it in 100s of razor pages where I post/get/delete data.
MaxConnectionsPerServerothers your requests would be queued. You should also consider to move the authorization header handling into a dedicated DelegatingHandler. Please also consider to use type client over named client.AddScoped()can be misleading - your scope belongs to the SignalR Circuit