Skip to content

Commit

Permalink
Change how ReCaptchaService consumes HttpClient (#14544)
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeAlhayek authored Oct 19, 2023
1 parent e228e45 commit a0844d9
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static IServiceCollection AddReCaptcha(this IServiceCollection services,
{
// c.f. https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
services.AddScoped<ReCaptchaService>()
.AddHttpClient<ReCaptchaService>()
.AddHttpClient(nameof(ReCaptchaService))
.AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(0.5 * attempt)));

services.AddSingleton<IDetectRobots, IPAddressRobotDetector>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,23 @@ public class ReCaptchaService
};

private readonly ReCaptchaSettings _reCaptchaSettings;
private readonly HttpClient _httpClient;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IEnumerable<IDetectRobots> _robotDetectors;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger _logger;
protected readonly IStringLocalizer S;
private HttpClient _httpClient;

public ReCaptchaService(
HttpClient httpClient,
IHttpClientFactory httpClientFactory,
IOptions<ReCaptchaSettings> optionsAccessor,
IEnumerable<IDetectRobots> robotDetectors,
IHttpContextAccessor httpContextAccessor,
ILogger<ReCaptchaService> logger,
IStringLocalizer<ReCaptchaService> stringLocalizer)
{
_httpClientFactory = httpClientFactory;
_reCaptchaSettings = optionsAccessor.Value;
_httpClient = httpClient;
_robotDetectors = robotDetectors;
_httpContextAccessor = httpContextAccessor;
_logger = logger;
Expand Down Expand Up @@ -123,6 +124,7 @@ private async Task<bool> VerifyAsync(string responseToken)
{ "response", responseToken }
});

_httpClient ??= _httpClientFactory.CreateClient(nameof(ReCaptchaService));
var response = await _httpClient.PostAsync($"{_reCaptchaSettings.ReCaptchaApiUri.TrimEnd('/')}/siteverify", content);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ReCaptchaResponse>(_jsonSerializerOptions);
Expand Down

0 comments on commit a0844d9

Please sign in to comment.