Cloudflare
How to solve Cloudflare Turnstile in C#
This guide builds a strongly typed Turnstile client for .NET with records and System.Text.Json, then uses Selenium WebDriver to put the token where the page expects it.
What you will build
The client has three parts: records that describe the task and the replies, a method that sends one API call, and a method that solves a Turnstile widget end to end. Typed records cost a few more lines than dictionaries, but they make the shape of the API visible in code reviews and give you compile time errors instead of ERROR_INVALID_TASK_DATA at run time. The Selenium part then reads the widget's attributes, asks the client for a token and writes it into the form.
Everything targets .NET 8. Add the Selenium.WebDriver package for the browser part; the client itself needs nothing beyond the base library.
Model the API with records
Attributes fix the JSON names, so the C# properties can follow .NET naming. JsonIgnore with WhenWritingNull drops optional fields such as Metadata when they are not set.
using System.Text.Json.Serialization;
public sealed record TurnstileMeta(
[property: JsonPropertyName("action"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? Action,
[property: JsonPropertyName("cdata"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? CData);
public sealed record TurnstileTask(
[property: JsonPropertyName("websiteURL")] string PageUrl,
[property: JsonPropertyName("websiteKey")] string SiteKey,
[property: JsonPropertyName("metadata"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] TurnstileMeta? Metadata)
{
[JsonPropertyName("type")] public string Type => "AntiTurnstileTaskProxyLess";
}
public sealed record TurnstileSolution(
[property: JsonPropertyName("token")] string Token,
[property: JsonPropertyName("userAgent")] string? UserAgent);
public sealed record GateReply(
[property: JsonPropertyName("errorId")] int ErrorId,
[property: JsonPropertyName("errorCode")] string? ErrorCode,
[property: JsonPropertyName("taskId")] string? TaskId,
[property: JsonPropertyName("status")] string? Status,
[property: JsonPropertyName("solution")] TurnstileSolution? Solution);
The Type property is computed, so nobody can construct a task with a misspelled type name. Note the field name websiteURL: the capital URL is part of the API, and the attribute keeps it exact.
Send requests and poll
This version serializes with JsonSerializer into a StringContent, which makes the request body easy to log while you develop.
using System.Text;
using System.Text.Json;
public sealed class TurnstileClient
{
private readonly HttpClient _http; // shared, thread safe
private readonly string _apiKey;
public TurnstileClient(HttpClient http, string apiKey) { _http = http; _apiKey = apiKey; }
private async Task<GateReply> CallAsync(string method, object payload, CancellationToken ct)
{
var json = JsonSerializer.Serialize(payload);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await _http.PostAsync("https://gatesolver.com/" + method, content, ct);
var reply = await JsonSerializer.DeserializeAsync<GateReply>(await response.Content.ReadAsStreamAsync(ct), cancellationToken: ct)
?? throw new InvalidDataException("Empty reply from " + method);
if (reply.ErrorId != 0) throw new HttpRequestException($"GateSolver {reply.ErrorCode}");
return reply;
}
public async Task<TurnstileSolution> SolveAsync(TurnstileTask task, CancellationToken ct = default)
{
var created = await CallAsync("createTask", new { clientKey = _apiKey, task }, ct);
var stopAt = DateTime.UtcNow.AddSeconds(124);
while (DateTime.UtcNow < stopAt)
{
await Task.Delay(3000, ct);
var state = await CallAsync("getTaskResult", new { clientKey = _apiKey, taskId = created.TaskId }, ct);
if (state.Status == "ready" && state.Solution is { } s) return s;
if (state.Status == "failed") throw new InvalidOperationException("Turnstile task failed (not billed)");
}
throw new TimeoutException("Turnstile token did not arrive in time");
}
}
Anonymous objects keep the envelope short; their property names are written exactly as declared, so clientKey and taskId come out right without a naming policy. The deadline is a wall clock check instead of a linked token, a simpler choice when the caller's token is enough for cancellation.
Insert the token with Selenium .NET
A static Turnstile widget is a div with class cf-turnstile. Once it renders, a hidden input named cf-turnstile-response appears inside the form. Read the attributes, solve, then set the input and run any declared callback.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome; // ChromeDriver and ChromeOptions
using OpenQA.Selenium.Support.UI;
var client = new TurnstileClient(new HttpClient(), Environment.GetEnvironmentVariable("GATE_KEY")!);
var options = new ChromeOptions();
options.AddArgument("--window-size=1280,900");
using var chrome = new ChromeDriver(options);
const string target = "https://support.example.org/ticket/new";
chrome.Navigate().GoToUrl(target);
var widget = new WebDriverWait(chrome, TimeSpan.FromSeconds(15))
.Until(d => d.FindElement(By.CssSelector(".cf-turnstile[data-sitekey]")));
var meta = new TurnstileMeta(widget.GetDomAttribute("data-action"), widget.GetDomAttribute("data-cdata"));
var solved = await client.SolveAsync(new TurnstileTask(target, widget.GetDomAttribute("data-sitekey")!,
meta.Action is null && meta.CData is null ? null : meta));
((IJavaScriptExecutor)chrome).ExecuteScript("""
const [token, cbName] = arguments;
document.querySelectorAll('input[name="cf-turnstile-response"]').forEach(i => i.value = token);
if (cbName && typeof window[cbName] === 'function') window[cbName](token);
""", solved.Token, widget.GetDomAttribute("data-callback"));
chrome.FindElement(By.CssSelector("form button[type=submit]")).Click();
The raw string literal (C# 11 and later) holds the script without escaping quotes. Both arguments arrive in JavaScript as arguments[0] and arguments[1]; destructuring them keeps the script readable. When the attribute is absent, GetDomAttribute returns null, which the script treats as "no callback".
Browser or plain HTTP?
Selenium is the safe default when you do not know how a form consumes its token. Once you do, plain HTTP is often enough and much lighter. If the form posts cf-turnstile-response as an ordinary field, use an HttpClient with a CookieContainer to load the page, read the site key and hidden fields with an HTML parser such as AngleSharp, solve with the same TurnstileClient, and post a FormUrlEncodedContent. Send the UserAgent from the solution as your User-Agent header for consistency. Keep the browser for forms whose callback builds a JSON request or adds values you cannot easily reproduce.
Lifetime and dependency injection
In an ASP.NET Core or worker service, register the client as a typed client with services.AddHttpClient<TurnstileClient>() and supply the API key from configuration or a secrets store through the constructor. The factory takes care of handler rotation, so you avoid both stale DNS and socket exhaustion. In a test project, a single static HttpClient shared by all tests is simpler and works just as well.
Widgets rendered from code
If there is no cf-turnstile div, the page calls turnstile.render() itself. Search the scripts for turnstile.render to find the site key, action, cData and callback, or record the options at run time as described in the Turnstile parameters guide. With Selenium 4 and Chrome you can inject such a recorder before page scripts run through the DevTools command Page.addScriptToEvaluateOnNewDocument, available via ExecuteCdpCommand on ChromeDriver.
Errors and retries
The client throws HttpRequestException with the API code in the message for error replies, InvalidOperationException for failed tasks and TimeoutException when the window closes. A small wrapper can retry the free, temporary cases (unsolvable, service unavailable, failed, timeout) once or twice, and let configuration problems such as a missing key or empty balance surface immediately. Keep the submit close to the solve: Cloudflare documents Turnstile tokens as valid for 300 seconds and good for one verification.
Reading the result of the submit
After the click, wait for something that only a successful submit produces: a URL change checked with WebDriverWait and a lambda such as d => d.Url.Contains("submitted"), a confirmation element, or the disappearance of the form. A page that reloads with the form still visible usually means the server refused the token or another field. Capture the page source on failure and store it next to the task id; the error message the site shows is often specific enough to tell a stale token from a validation problem.
Testing tips
For your own sites, Cloudflare publishes dummy Turnstile site keys and secret keys that always pass or always fail, intended for automated tests. Use those in staging and keep the solver for runs against the real configuration. When you do run against real widgets, log the task id and submit time so you can line up any refusals with timing. A solved Turnstile task costs $0.84 per 1,000, failures are free, and answers usually arrive under 3 seconds. More Selenium patterns are in the Selenium integration guide; fields are listed on the Turnstile task page.
Common questions
Why use records instead of anonymous objects for the task?
Records fix field names and the type string at compile time, so typos fail in the build rather than as API errors.
Which .NET version is needed?
.NET 8 is the target. The raw string literal needs C# 11, and records need C# 9.
What if data-action is not set?
Leave metadata out. The record and JsonIgnore settings drop null values from the request.
Can I reuse one HttpClient for many solves?
Yes. HttpClient is designed to be shared, and the client class keeps no per call state.
Does Turnstile have test keys for my own site?
Yes. Cloudflare publishes dummy site and secret keys for automated testing; use them in staging.
Keep reading
- SeleniumThe reference Selenium setup in Python and Java: explicit waits, reCAPTCHA v2 and Turnstile tokens, callbacks, retries and Grid scaling.
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.
- Find Turnstile site key, action and cDataWhere Turnstile keeps its site key, action and cData: widget attributes, turnstile.render options and explicit rendering setups.
- Cloudflare TurnstileThe Turnstile widget from Cloudflare, its managed, non-interactive and invisible modes, and the cf-turnstile-response token field.