0

I am building an API which exposes a POST endpoint which accepts environment details containing keys which map to uris) in the request. Then this API depending on the request data passed, will send POST requests to other APIs.

Untill now, the base uri of the client was static, now the uri is dynamic and is passed from the incoming request.

The HttpClient is built in a Service class when injected through the constructor.

How can I add CredentialsCache on client that has already been built by the constructor and moce the logic from startup to on demand request?

Currently registered on Startup using an extension method

public static IServiceCollection AddUnderTest(this IServiceCollection services, ClientA settings)
    {
        var client = services
            .AddHttpClient(
            nameof(ClientA),
            c => { c.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); });

        client.ConfigurePrimaryHttpMessageHandler(
            handler => new HttpClientHandler
            {
                Credentials = new CredentialCache { {
                    new Uri(""),
                    "Digest",
                    new NetworkCredential(settings.Username, settings.Password) } }
            });
        return services;
    }

in service class

public class MyService
{

    public MyService(IHttpClientFactory htpClientFactory)
    {
        var myClient = htpClientFactory.CreateClient("ClientA");
        //add digest auth and credentials here, and not on startup
    }
}

How can I add the same configuration as in the extension methon on startup?

Vergil C.
  • 1,046
  • 2
  • 15
  • 28
  • don't inject `IHttpClientFactory` - just register a strongly typed client. – Daniel A. White Jan 30 '19 at 16:02
  • Could you give me an example please? – Vergil C. Jan 30 '19 at 16:03
  • https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#implement-your-typed-client-classes-that-use-the-injected-and-configured-httpclient – Daniel A. White Jan 30 '19 at 19:02
  • @VergilC. Did his comment answer your question? Because I'm stuck at something familiar and wondering if I need to re-write my service where Im using the Ihttpclientfactory – Carsten May 04 '22 at 12:03
  • 1
    @Carsten to be honest I don't remember, but we don't use typed clients. With named client and using the extension `ConfigureHttpMessageHandlerBuilder` and inside just adding new handler `builder.PrimaryHandler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) };` worked fine for digest auth. This may help you https://stackoverflow.com/questions/50747749/how-to-use-httpclienthandler-with-httpclientfactory-in-net-core – Vergil C. May 09 '22 at 10:23

0 Answers0