twitchax / AspNetCore.Proxy

ASP.NET Core Proxies made easy.
MIT License
505 stars 80 forks source link

NullReferenceException when GetService<IHttpClientFactory>() fails #98

Open plutora-steve-g opened 2 years ago

plutora-steve-g commented 2 years ago

In ExecuteHttpProxyOperationAsync the following code throws if IHttpClientFactory is not registered. Wasn't obvious to me what the cause was, ended up downloading the code and stepping through

                var httpClient = context.RequestServices
                    .GetService<IHttpClientFactory>()
                    .CreateClient(options?.HttpClientName ?? Helpers.HttpProxyClientName);

Perhaps something along these lines:

                var clientFactory = context.RequestServices.GetService<IHttpClientFactory>()
                     ?? throw new InvalidOperationException("IHttpClientFactory not registered. You need to add builder.Services.AddHttpClient(); during startup");
                var httpClient = clientFactory.CreateClient(options?.HttpClientName ?? Helpers.HttpProxyClientName);
twitchax commented 2 years ago

Good idea: if you want to make the PR, then you can get credit. 😄

Otherwise, I am happy to do it.