Home > Net >  Returned HttpClient does not have the configuration I saved into the service collection
Returned HttpClient does not have the configuration I saved into the service collection

Time:01-14

For an asp.net web forms application, I am attempting to generate an httpclient from an httpclientfactory. However, the returned httpclient does not have the configuration (the base address and headers) that I configured in the GetHttpClientFactory method.

public static class HttpClientFactory
{
    private static IHttpClientFactory _httpClientFactory;
    private const string _ClientKey = "MyClient";

    public static IHttpClientFactory GetHttpClientFactory()
    {
        if (_httpClientFactory != null)
        {
            return _httpClientFactory;
        }
        var serviceCollection = new ServiceCollection();

        serviceCollection.AddHttpClient(_ClientKey, client =>
            {
                client.BaseAddress = new Uri("http://localhost:36338");
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("User-Agent", "Demo");
            })
            .ConfigurePrimaryHttpMessageHandler(() =>
                new HttpClientHandler
                {
                    Credentials = new NetworkCredential("accountname", "password")
                });
        var serviceProvider = serviceCollection.BuildServiceProvider();
        _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
        
        return _httpClientFactory;
    }

}

Here is where I am calling into the factory to generate the client.

protected async void Page_Load(object sender, EventArgs e)
    {
        //RegisterAsyncTask(new PageAsyncTask(GetDivisions));
        var loggerFactory = LoggerFactory.Create(builder => {
            builder.AddFilter("Microsoft", LogLevel.Warning);
            });
        var httpClient = HttpClientFactory.GetHttpClientFactory();
        var commonServices = new ServiceWrapper(loggerFactory.CreateLogger<ServiceWrapper>(), httpClient);
        var divisions = await commonServices.GetDivisions();
        foreach (var d in divisions)
            AddTableRow(Table1, d.Id, d.Name);
    }

Each time I make a web request, I get an exception that "An invalid request URI was provided".

CodePudding user response:

I'm pretty much sure that you are calling CreateClient without providing the client name. Try next in your ServiceWrapper:

// 1. not sure how the second parameter of ServiceWrapper is called
// 2. Possibly make HttpClientFactory._ClientKey public so no need for magic string
var result = httpClientFactory.CreateClient("MyClient"); 
  •  Tags:  
  • Related