1

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.

5
  • The approach is more or less solid. You might need to increase the MaxConnectionsPerServer others 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. Commented Jul 22 at 8:22
  • The AddScoped() can be misleading - your scope belongs to the SignalR Circuit Commented Jul 22 at 9:31
  • Using the HttpContextAccessor this way is not advisable. Commented Jul 22 at 9:34
  • Thank you all. I will take your comments into my consideration. Thanks once again! Commented Jul 22 at 10:24
  • Since you're on the server, use of the IHttpContextAccessor is fine but I would make it more elegant by using a DelegatingHandler. Commented Jul 22 at 17:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.