GeeTest v4 in C#: GeetestV4Async and IHttpClientFactory

geetest v4 in c# - GeeTest v4 in C#: GeetestV4Async and IHttpClientFactory

To use GeeTest v4 in C#, read the one public captcha_id from the page, call GeetestV4Async from the CapSkip NuGet package once per form submission, and post the five values it returns under their own names. This post builds that as a small .NET console host. A typed HttpClient from IHttpClientFactory talks to the site, one CapSkipClient talks to the solver on your own Windows PC, and a semaphore keeps a batch of submissions from all solving at once. The product side is on the GeeTest v4 solver page, and there is no fee per solve.

What you need

  • A CapSkip build that lists GeeTest v4, running on a Windows PC. The setup guide gets it going. I could not check which app version I had, because the app was not answering on this PC.
  • The .NET 8 SDK or later and the CapSkip package at 1.8.0 or newer, the first release with GeetestV4Async (changelog entry dated 2026-11-16). The package itself targets .NET Standard 2.0, but the sample below uses C# 12 syntax and the Microsoft.Extensions packages, so I ran it on net8.0 and net10.0 only. Only SDK 10.0.100 is installed here, so net8.0 was built by changing the TargetFramework line and run on the 8.0 runtime.
  • A page you may automate that shows a GeeTest v4 widget, and the address of the form it posts to.
  • An address for CapSkip. In Local mode only the PC that runs it can reach 127.0.0.1. Server mode makes the API reachable from other machines too, and the setup guide explains both modes under connection settings.

I could not reach a running CapSkip app when I tested, so no real solve ran and no real site was contacted. Every result below comes from a mock I wrote that plays in.php, res.php and a site with a comment form. The mock follows the SDK’s API reference, and its site rules are mine, not those of GeeTest. Where a statement rests on documentation or on reading the SDK source, I say so.

Step 1: create the host and a typed client for the site

Make a project folder and install the three packages. I tested net8.0 and net10.0 only.

dotnet new console -o GeetestWorker
cd GeetestWorker
dotnet add package CapSkip
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.Http

Only on net8.0, swap the last two commands for these pinned ones. The newest 11.0.0 packages build on net8.0 but print an unsupported-framework warning for each package, and the pinned versions built with none.

# Only on net8.0: use these instead of the two Microsoft.Extensions lines above.
dotnet add package Microsoft.Extensions.Hosting --version 8.0.1
dotnet add package Microsoft.Extensions.Http --version 8.0.1

The next three C# blocks are files for the project folder, and each starts with its file name. Save them in the order shown. The last one, Program.cs, replaces the file the template generated.

The typed client belongs to the target site only. Reading the SDK source, CapSkipClient builds its own static HttpClient internally and has no constructor that takes yours, so IHttpClientFactory helps with your own calls and nothing else. SiteClient does two jobs: it reads the captcha_id, and it posts the form.

// SiteClient.cs
using System.Text.RegularExpressions;
using CapSkip;

// The typed client talks to the target site only. CapSkipClient has its own HttpClient.
public sealed class SiteClient(HttpClient http)
{
    // Finds captchaId with either quote style, however deeply the call is nested.
    static readonly Regex IdPattern = new(@"captchaId[""']?\s*:\s*[""']([0-9a-fA-F]{32})[""']");

    public async Task<string> ReadCaptchaIdAsync(string pageUrl, CancellationToken ct)
    {
        var html = await http.GetStringAsync(pageUrl, ct);
        var m = IdPattern.Match(html);
        return m.Success ? m.Groups[1].Value : throw new InvalidOperationException("no captchaId on " + pageUrl);
    }

    // The five values go back under GeeTest's own names. "text" is this form's field.
    public async Task<string> PostAsync(string pageUrl, string formUrl, SolveResult r, string text, CancellationToken ct)
    {
        using var form = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["captcha_id"] = r.GeetestCaptchaId!,
            ["lot_number"] = r.LotNumber!,
            ["pass_token"] = r.PassToken!,
            ["gen_time"] = r.GenTime!,
            ["captcha_output"] = r.CaptchaOutput!,
            ["text"] = text,
        });
        using var request = new HttpRequestMessage(HttpMethod.Post, formUrl) { Content = form };
        request.Headers.Referrer = new Uri(pageUrl);  // many frameworks check it on a form post
        using var response = await http.SendAsync(request, ct);
        return $"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync(ct)}";
    }
}

GeeTest v4 has no challenge to fetch per request, unlike the v3 flow in the GeeTest v3 in C# post. The page passes one id, the same for every visitor, to initGeetest4 as captchaId, so you read it once and reuse it. When the page builds that call at runtime, the SDK docs point to the captcha_id query parameter of the request to gcaptcha4.geetest.com/load in the browser’s Network tab. The regular expression matched three mock pages as I expected: a call with double quotes, a call with single quotes nested inside two objects, and a page with no id, which threw the InvalidOperationException.

Two details of the client come from runs. The factory pools its message handlers, and the default one keeps a single cookie jar for every request: across three GETs the second and third carried the cookie the previous response had set. With UseCookies set to false, as in Program.cs below, none did (mock, net10.0 and net8.0). If your form needs the session cookie from the page, read Set-Cookie per submission and send it back yourself. HttpClient also adds no Referer on its own: with that line removed the mock saw an empty header, which is why the code sets it.

Step 2: one solve per submission

GeetestV4Async takes the captcha_id, the page address, an optional dictionary of options and a CancellationToken. It returns a SolveResult. The class below is the unit that solves and then posts, and a SemaphoreSlim of three limits how many solves run at once. Pick a number your CapSkip PC can handle, since three is only my mock setting.

// Submitter.cs
using CapSkip;

public sealed class Submitter(CapSkipClient solver, SiteClient site)
{
    // At most 3 solves in flight. Size this to what your CapSkip PC can take.
    readonly SemaphoreSlim gate = new(3);

    public async Task<string> SubmitAsync(string captchaId, string pageUrl, string formUrl, string text, CancellationToken ct)
    {
        SolveResult result;
        await gate.WaitAsync(ct);
        try
        {
            // One solve per submission: this result is used for one form post and dropped.
            result = await solver.GeetestV4Async(captchaId, pageUrl, cancellationToken: ct);
        }
        finally { gate.Release(); }

        // The site decides whether an offline pass counts, so do not send it blindly.
        if (result.IsOffline == true) return "offline pass, not sent";
        return await site.PostAsync(pageUrl, formUrl, result, text, ct);
    }
}

The result carries the five values as GeetestCaptchaId, LotNumber, PassToken, GenTime and CaptchaOutput, all strings. The first one is not CaptchaId because that name is already the id CapSkip gives the solve (the mock handed out 9101 and up), which the changelog explains. Code keeps the raw JSON string the API sends, and in the mock run Token and Challenge were null, since they belong to other types.

Why solve per submission? The SDK’s own example says to solve again for every submission, and my mock enforces it: posting one result twice got a 403 whose body said the pass token was already used. That is the mock’s rule. The GeeTest server validation page I read does not say whether a pass can be used twice, so keep to the SDK’s advice. The CapSkip docs also say to submit promptly, and the GeeTest page says an expired pass_token fails validation, which is the stronger reason to solve per submission.

Who checks the result? The site’s own server. Per the GeeTest server validation docs (the page is in Chinese), it sends lot_number, captcha_output, pass_token and gen_time to GeeTest, plus captcha_id and a sign_token, an HMAC-SHA256 of lot_number made with the site’s private key. CapSkip never sees that key, and your code does not need it.

IsOffline is a nullable bool. Per the docs it is true when GeeTest could not be reached and its widget passed without a challenge, and the site then decides whether to accept it. The SDK reads true, the word true in any letter case and a nonzero number as true, zero and the word false as false, and anything it cannot read as null (mock answers, all six forms). The code above skips an offline pass. If your site accepts them, delete that line.

Both options are optional. This snippet replaces the GeetestV4Async call in Submitter.cs:

// Snippet, not a file: replace the GeetestV4Async call in Submitter.cs with this one.
result = await solver.GeetestV4Async(captchaId, pageUrl, new Dictionary<string, object?>
{
    ["risk_type"] = "slide",
    ["proxy"] = new Proxy("HTTP", "login:[email protected]:8080"),
}, ct);

Per the docs, risk_type takes one of ten values: slide, icon, nine, word, phrase, match, winlinze, svg_seed, svg_icon and ai. GeeTest applies one only where the site allows callers to choose. The SDK does not check the value: it trimmed whitespace, dropped a blank one and sent a nonsense value unchanged, and it refused a number with a ValidationException. The spelling riskType works as an alias. Use proxy when the site needs the same address for the solve and the form post, as the CAPTCHA solver proxy post explains. A bare address string means HTTP, and a type outside HTTP, HTTPS, SOCKS5 and SOCKS5H is refused locally.

For a concurrent batch, think about the network too. The CapSkip API docs say GeeTest scores the network, and a steady stream of requests from one address is what its rate limiting catches. Add a proxy pool in the CapSkip app under Settings, Captcha types, GeeTest, Configure Proxies. One pool serves both v3 and v4, and a proxy you send with a task wins over the pool.

Step 3: run several submissions at once

Program.cs makes the host only for its dependency container, so it never calls RunAsync. It reads the captcha_id once, starts five submissions together and prints each outcome. The five placeholders are your own form texts. Change PageUrl and FormUrl first, since as pasted they point at example.com, which has no widget.

// Program.cs
using CapSkip;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
// Implicit usings import System, which has a TimeoutException too.
using SolverTimeout = CapSkip.TimeoutException;

const string PageUrl = "https://example.com/login";   // the page that shows the widget
const string FormUrl = "https://example.com/comment";  // where its form posts

var builder = Host.CreateApplicationBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Warning);  // the host logs every HttpClient call at Information
// Local mode. In Server mode use the server's address, and pass apiKey if validation is on.
builder.Services.AddSingleton(new CapSkipClient(host: "127.0.0.1", port: 8080));
// The factory's pooled handler keeps one cookie jar for every request, so switch it off.
builder.Services.AddHttpClient<SiteClient>(c => c.Timeout = TimeSpan.FromSeconds(20))
    .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { UseCookies = false });
builder.Services.AddSingleton<Submitter>();
using var host = builder.Build();

using var budget = new CancellationTokenSource(TimeSpan.FromMinutes(2));
Console.CancelKeyPress += (_, e) => { e.Cancel = true; budget.Cancel(); };

var site = host.Services.GetRequiredService<SiteClient>();
var submitter = host.Services.GetRequiredService<Submitter>();
var texts = new[] { "first", "second", "third", "fourth", "fifth" };

string captchaId;
try { captchaId = await site.ReadCaptchaIdAsync(PageUrl, budget.Token); }
catch (Exception ex) { Console.WriteLine("could not read the captcha id: " + ex.Message); return 1; }

var results = await Task.WhenAll(texts.Select(async text =>
{
    try { return await submitter.SubmitAsync(captchaId, PageUrl, FormUrl, text, budget.Token); }
    catch (Exception ex) { return Describe(ex); }  // one failure must not hide the others
}));

for (var i = 0; i < texts.Length; i++) Console.WriteLine($"{texts[i]}: {results[i]}");
return results.All(r => r.StartsWith("200")) ? 0 : 1;

string Describe(Exception ex) => ex switch
{
    // A cancelled submit surfaces as a NetworkException, a cancelled poll as a TaskCanceledException.
    _ when budget.IsCancellationRequested => "the budget ran out",
    ValidationException => "CapSkip refused the arguments: " + ex.Message,
    ApiException => "CapSkip answered " + ex.Message,
    SolverTimeout => "no answer in time: " + ex.Message,
    NetworkException => "CapSkip is not reachable: " + ex.Message,
    // HttpClient reports its own timeout as a TaskCanceledException.
    TaskCanceledException => "the site did not answer within 20 seconds",
    HttpRequestException => "the site could not be reached: " + ex.Message,
    _ => ex.GetType().Name + ": " + ex.Message,
};

Each submission wraps its own try block. Task.WhenAll rethrows only the first failure and cancelled tasks carry no exception to read, so catching inside the lambda keeps every outcome. Start the program with dotnet run. These rows are mock results, and they were identical on net10.0 and net8.0.

Mock settingWhat the program printed
Default mock settingsFive lines of 200 and the text, exit code 0
Each solve ready after 2 secondsAt most 3 solves in flight, the last two submitted 3.8 seconds after the first three, and the whole run took about 8 seconds
First two solves failTwo lines with the API error, three with 200, exit code 1
The mock site refuses two form posts with 403Two 403 lines, three 200 lines, and nothing retried
Every answer carries isOffline trueFive lines of offline pass, not sent, exit code 1

Cancellation and the two TimeoutExceptions

The CancellationToken reaches both the SDK and HttpClient, so one budget covers the whole batch. With a mock that never finishes and a 3 second budget, all five lines read that the budget ran out and the process ended after about 3.5 seconds. Cancelling while in.php hung gave a NetworkException that wraps a TaskCanceledException, and cancelling during polling gave a plain TaskCanceledException. Checking the budget token first in Describe handles both.

CapSkip also throws its own TimeoutException when polling runs past its limit, and implicit usings import System, which has one too. A bare catch for TimeoutException next to using CapSkip failed to compile with CS0104, which is why Program.cs aliases the SDK’s class as SolverTimeout. HttpClient does not throw System.TimeoutException at you, though. With the mock site sleeping 25 seconds and the client limit at 20, every submission came back as a TaskCanceledException after about 20 seconds, and the run took about 20.6 seconds in all.

GeetestV4Async uses recaptchaTimeout, which is 300 seconds by default, not defaultTimeout (per the changelog). I checked it: with defaultTimeout 1 and recaptchaTimeout 5 against a mock that never answered, the exception arrived after 7.87 seconds on net10.0 and 7.85 on net8.0. The SDK polls at about 0, 0.25, 0.75, 1.75 and 3.75 seconds and then sleeps 4 more, so the deadline is noticed when that last sleep ends, well after the 5 seconds you set.

Common errors

What you seeCauseFix
ValidationExceptionRefused before any request: a blank captcha_id, a page address that is not absolute http or https, a risk_type that is not a string, or an option such as gt or challenge from v3Fix the argument. Retrying cannot help
ApiException with ERROR_KEY_DOES_NOT_EXISTThe mock rejected the key. Per the docs, the real app answers this when API Key Validation is on and the key is unknownPass the key in CapSkipClient
ApiException with ERROR_CAPTCHA_UNSOLVABLEThe solve failed. I produced it with a mock, and could not check how the real app reports a failed v4 solveSolve again, and never post the old result
NetworkExceptionNothing answered at the CapSkip host and port, or the call was cancelledStart CapSkip, or check the host in CapSkipClient
CapSkip TimeoutExceptionPolling passed recaptchaTimeout, and the SDK notices only when its next sleep endsRaise recaptchaTimeout if your solves are slow
The site answers 403 or 400In my mock: a result already used, a missing field, or an offline pass. A real site sets its own rulesPost all five fields from one fresh solve

Server mode: solver and host on separate machines

This host can run on a second PC while CapSkip stays on a Windows machine you control. Switch Server mode on in the connection settings of the solver PC, then put that PC’s address in the host argument of CapSkipClient. Nothing else in the code changes. Server mode needs CapSkip to run as administrator, per the setup guide. The setup guide recommends a static public IP for stable access, and it explains the connection settings in full.

When Server mode starts, CapSkip opens its port to every address. To keep it to the machines you expect, add a Windows Firewall block rule for all others, and turn on API Key Validation so that CapSkipClient must present a key.

FAQ

Why is the result property called GeetestCaptchaId?

CaptchaId was taken: it is the id CapSkip gives the solve. GeetestCaptchaId holds the GeeTest captcha_id that the widget echoes, and it is one of the five fields the site expects back.

Can I share one CapSkipClient across threads?

I ran five solves at once through a single instance with no problem in the mock, and the source copies its parameters per call. I did not test it beyond that. If you register it as a singleton, as above, the semaphore is what limits the load.

GeeTest v4 in C# comes down to one captcha_id read, one GeetestV4Async call per submission and five fields posted together. CapSkip is a flat-license captcha solver that runs on your own PC, so every extra solve after a refusal is free. For the other types in .NET, see the C# CAPTCHA solver page, and for the request format read the GeeTest v4 section of the API docs.