reCAPTCHA
How to solve reCAPTCHA v2 in C#
This guide writes a small async client for .NET 8 that returns reCAPTCHA v2 tokens, then uses it from a Selenium WebDriver test. Each solve costs $0.56 per 1,000 and arrives under 9 seconds in most cases.
The shape of the solution
In .NET the natural design is a typed client class that receives an HttpClient through its constructor. That fits IHttpClientFactory in ASP.NET Core and worker services, and it is just as easy to new up in a console app or an NUnit fixture. The class exposes one async method, takes a CancellationToken, and returns the token string.
Selenium then does what it is good at: loading the page, reading the site key, writing the token into the page and clicking submit. The browser never has to interact with the checkbox itself.
Write the client class
The client below uses a C# 12 primary constructor and System.Net.Http.Json, which ships with .NET. Requests are built as dictionaries so the JSON keys keep their exact spelling; websiteURL has an unusual capital pattern that a naming policy could otherwise alter.
using System.Net.Http.Json; // PostAsJsonAsync and ReadFromJsonAsync
using System.Text.Json;
public sealed class GateException(string code, string detail) : Exception($"{code}: {detail}")
{
public string Code { get; } = code;
}
public sealed class GateClient(HttpClient http, string clientKey)
{
public async Task<string> SolveRecaptchaV2Async(string pageUrl, string siteKey, CancellationToken ct = default)
{
var created = await SendAsync("createTask", new()
{
["task"] = new Dictionary<string, object>
{
["type"] = "ReCaptchaV2TaskProxyLess", // checkbox, solved without a proxy
["websiteURL"] = pageUrl,
["websiteKey"] = siteKey,
},
}, ct);
var taskId = created.GetProperty("taskId").GetString()!;
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(TimeSpan.FromSeconds(125));
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(3), limit.Token);
var poll = await SendAsync("getTaskResult", new() { ["taskId"] = taskId }, limit.Token);
switch (poll.GetProperty("status").GetString())
{
case "ready":
return poll.GetProperty("solution").GetProperty("gRecaptchaResponse").GetString()!;
case "failed":
throw new GateException("FAILED", "task failed, no charge");
}
}
}
The private helper below completes the GateClient class; it attaches the key and turns API errors into exceptions:
private async Task<JsonElement> SendAsync(string method, Dictionary<string, object> body, CancellationToken ct)
{
body["clientKey"] = clientKey;
using var resp = await http.PostAsJsonAsync($"https://gatesolver.com/{method}", body, ct);
var json = await resp.Content.ReadFromJsonAsync<JsonElement>(ct);
if (json.TryGetProperty("errorId", out var id) && id.GetInt32() != 0)
throw new GateException(json.GetProperty("errorCode").GetString()!,
json.TryGetProperty("errorDescription", out var d) ? d.GetString() ?? "" : "");
return json;
}
}
The linked token source gives every solve its own ceiling of 125 seconds while still honouring the caller's token. When either one fires, Task.Delay throws TaskCanceledException and the method exits without another poll.
Register it for dependency injection
In a host based app, add the client with builder.Services.AddHttpClient<GateClient>() and pass the key from configuration through a small factory, or wrap the key in an options class. The factory manages handler lifetimes for you, which avoids the socket exhaustion problems that come from creating a fresh HttpClient per call. In a short console tool, one static HttpClient with Timeout = TimeSpan.FromSeconds(30) is perfectly fine.
Inject the token with Selenium
Selenium's IJavaScriptExecutor runs a script in the page and passes your token as an argument, so you never build JavaScript by string concatenation.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
var gate = new GateClient(new HttpClient { Timeout = TimeSpan.FromSeconds(30) },
Environment.GetEnvironmentVariable("GATE_KEY") ?? "YOUR_API_KEY");
using var driver = new ChromeDriver();
var url = "https://example.com/newsletter";
driver.Navigate().GoToUrl(url);
var siteKey = driver.FindElement(By.CssSelector("[data-sitekey]")).GetDomAttribute("data-sitekey");
var token = await gate.SolveRecaptchaV2Async(url, siteKey);
var js = (IJavaScriptExecutor)driver;
js.ExecuteScript(@"
const field = document.querySelector('textarea[name=""g-recaptcha-response""]');
field.value = arguments[0];
const cb = document.querySelector('[data-callback]')?.dataset.callback;
if (cb && typeof window[cb] === 'function') window[cb](arguments[0]);", token);
driver.FindElement(By.CssSelector("form button[type='submit']")).Click();
GetDomAttribute reads the attribute exactly as written in the markup and is the recommended call in Selenium 4; older code often uses GetAttribute, which may be marked obsolete in the version you install, so check the current Selenium release notes. The verbatim string uses doubled quotes inside the selector, which is how C# escapes a quote in @"...".
Using it in automated tests
Teams often meet reCAPTCHA in end to end tests for their own sign up or contact forms, typically in a staging copy that kept the production widget. Put the solve inside the test helper that submits the form, so each test gets a fresh token at the moment it needs one. Running tests in parallel is fine, because the API has no cap on concurrent tasks; the limit to watch is 600 requests a minute per key across the whole suite.
For tests, also consider asking your own back end team for a test key. Google documents special test keys that always pass, and for your own staging site that is cheaper than solving. Keep the solver path for the cases where you test against the real configuration.
Submitting without a browser
Selenium is convenient but heavy. If the form is a classic server rendered page, you can skip the browser entirely: fetch the page with an HttpClient that has a CookieContainer on its handler, parse the HTML with a library such as AngleSharp or HtmlAgilityPack to read the site key and hidden inputs, then post a FormUrlEncodedContent built from those values plus g-recaptcha-response. Use a separate HttpClient for the target site so its cookies and headers never mix with the calls to the solver.
The browserless route is faster and uses far less memory, which matters on build agents and in containers. The trade-off is that it only works when the form does not depend on JavaScript to assemble its request. Check by submitting the form once with developer tools open: if the request is a normal form post, the browserless route is open to you; if it is a JSON call built by a script, keep Selenium or copy that call exactly.
When the site checks the IP
Some back ends verify that the token was produced for a visitor on the same network as the submit. If proxyless tokens are refused while timing is correct, change the task type to ReCaptchaV2Task and add a proxy entry in the format http://user:pass@host:port, using the same proxy you configured on ChromeDriver through ChromeOptions.AddArgument("--proxy-server=...") or on your HttpClientHandler. Only one dictionary entry changes in the client; everything else stays as written.
Handling failures cleanly
Catch GateException and branch on Code. Retry ERROR_CAPTCHA_UNSOLVABLE and ERROR_SERVICE_UNAVAILABLE once or twice with a short delay; both are free. Fail fast on ERROR_ZERO_BALANCE, ERROR_KEY_DENIED_ACCESS and ERROR_INVALID_TASK_DATA, whose description names the missing field. A TaskCanceledException after 125 seconds means the task ran out of time and was not billed.
If the token is accepted by the API but refused by the site, check timing first (tokens last about two minutes), then whether the page is really the invisible variant described in solving invisible reCAPTCHA. More Selenium patterns live in the Selenium integration guide, and all task fields are on the reCAPTCHA v2 page.
Common questions
Which .NET version does this client target?
It uses a C# 12 primary constructor, so .NET 8 or newer. Replace it with a normal constructor to compile on older versions.
Why use dictionaries instead of a record for the task?
Dictionary keys are written exactly as given, so field names such as websiteURL keep their spelling under any JSON naming policy.
Can I share one GateClient across threads?
Yes. HttpClient is thread safe for sending requests, and the client holds no per call state.
How do I stop a solve when a test is cancelled?
Pass the test framework cancellation token into SolveRecaptchaV2Async; the linked token stops the polling loop.
Does Selenium need to click the checkbox?
No. The token is written into the hidden textarea with ExecuteScript, so the widget never needs a click.
Keep reading
- SeleniumThe reference Selenium setup in Python and Java: explicit waits, reCAPTCHA v2 and Turnstile tokens, callbacks, retries and Grid scaling.
- reCAPTCHA v2 solver$0.56 per 1,000 tasks, answers under 9 seconds.
- Solve invisible reCAPTCHA v2Spot the floating badge, send the task with isInvisible set, then hand the token to the page through its callback.
- SeleniumThe long standing browser automation project built on WebDriver, usable from many languages and scalable through Grid.