NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

More languages

How to solve image text CAPTCHAs in C#

This guide reads distorted text pictures from .NET: it downloads the image in the form session, encodes it with Convert.ToBase64String, sends an ImageToTextTask at $0.28 per 1,000, and submits the answer with FormUrlEncodedContent.

The pieces you need

A text CAPTCHA flow has three requests that must share one session: the form page, the picture, and the submit. In .NET that means one HttpClient built on a handler with a CookieContainer. Between the picture and the submit, the bytes go to the API as base64 and come back as text. The code targets .NET 8; earlier versions only need small syntax changes. For an overview of the challenge type, see image CAPTCHA.

Load the form and find the picture

Parse the HTML to find the image URL and the hidden fields. The example uses AngleSharp (dotnet add package AngleSharp), a widely used HTML parser for .NET; HtmlAgilityPack works just as well.

using System.Net;
using AngleSharp.Html.Parser;

var cookies = new CookieContainer();
using var web = new HttpClient(new HttpClientHandler { CookieContainer = cookies })
{
    Timeout = TimeSpan.FromSeconds(20)
};
var formPage = new Uri("https://licences.example.org/check");
var html = await web.GetStringAsync(formPage);
var doc = new HtmlParser().ParseDocument(html);

var imgSrc = doc.QuerySelector("img#captcha, img[src*='captcha']")?.GetAttribute("src")
             ?? throw new InvalidOperationException("captcha image not found");
var imgUri = new Uri(formPage, imgSrc);                 // resolves relative paths
var hidden = doc.QuerySelectorAll("form input[type=hidden][name]")
                .ToDictionary(i => i.GetAttribute("name")!, i => i.GetAttribute("value") ?? "");

Constructing new Uri(formPage, imgSrc) turns a relative src such as /captcha.ashx?r=123 into an absolute address. The dictionary collects hidden inputs such as __VIEWSTATE on ASP.NET Web Forms pages, which the submit must send back.

Download the bytes and encode them

byte[] pictureBytes = await web.GetByteArrayAsync(imgUri);
string pictureB64 = Convert.ToBase64String(pictureBytes);

Because web uses the same CookieContainer, the picture belongs to the session that loaded the form. Convert.ToBase64String returns plain base64 with no data URL prefix, which is exactly what the task's body field wants. Do not resize or re-encode the picture first; the original pixels give the best recognition.

Send the ImageToTextTask

A small static helper is enough. It uses JsonContent.Create to post anonymous objects and JsonDocument to read replies, and polls once a second, since image tasks finish quickly.

using System.Net.Http.Json; // JsonContent.Create
using System.Text.Json;

static class TextCaptcha
{
    static readonly HttpClient Api = new() { BaseAddress = new Uri("https://gatesolver.com/"), Timeout = TimeSpan.FromSeconds(25) };

    static async Task<JsonElement> Ask(string route, object body)
    {
        using var resp = await Api.PostAsync(route, JsonContent.Create(body));
        var root = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement.Clone();
        if (root.GetProperty("errorId").GetInt32() != 0)
            throw new InvalidOperationException($"{route}: {root.GetProperty("errorCode").GetString()}");
        return root;
    }

    public static async Task<string> ReadAsync(string base64, string apiKey)
    {
        var job = await Ask("createTask", new { clientKey = apiKey, task = new { type = "ImageToTextTask", body = base64 } });
        var id = job.GetProperty("taskId").ToString();
        for (int second = 0; second < 60; second++)
        {
            await Task.Delay(TimeSpan.FromSeconds(1));
            var r = await Ask("getTaskResult", new { clientKey = apiKey, taskId = id });
            switch (r.GetProperty("status").GetString())
            {
                case "ready": return r.GetProperty("solution").GetProperty("text").GetString()!;
                case "failed": throw new InvalidOperationException("picture could not be read; not charged");
            }
        }
        throw new TimeoutException("no text within a minute");
    }
}

Clone() detaches the element from the JsonDocument, so the returned value stays valid after the document is collected. ToString() on the task id works whether the API returns it as a string or a number.

Submit with FormUrlEncodedContent

string apiKey = Environment.GetEnvironmentVariable("GATESOLVER_KEY") ?? "YOUR_API_KEY";
string answer = await TextCaptcha.ReadAsync(pictureB64, apiKey);

var fields = new Dictionary<string, string>(hidden)
{
    ["LicenceNumber"] = "LN-448812",
    ["CaptchaText"] = answer,
};
using var post = await web.PostAsync(formPage, new FormUrlEncodedContent(fields));
var page = await post.Content.ReadAsStringAsync();
Console.WriteLine(page.Contains("Licence status", StringComparison.OrdinalIgnoreCase)
    ? "lookup succeeded" : "lookup failed, inspect the response");

Use the form's real action URL and field names. On ASP.NET Web Forms pages, the submit button's own name and value are usually required too; add them to the dictionary the way the browser sends them.

Keep the exact text

Send the answer character for character as it came back. Many sites compare case sensitively, and calling ToUpperInvariant() or trimming inner spaces can turn a right answer into a wrong one. Normalize only when you know the site's rules, for example digits only. The FAQ on image CAPTCHA case sensitivity explains the common patterns.

Tuning recognition

  • Add module = "common" or another module name to the task when one text style is read poorly.
  • Add score between 0.8 and 1 to receive only confident answers; weaker ones fail for free.
  • When the site says the code is wrong, reload the form for a fresh picture before trying again.

Running in a background service

In a BackgroundService or Azure Function that runs lookups on a schedule, create one HttpClient and CookieContainer per lookup so sessions do not mix, and keep the API client static or injected. With an IHttpClientFactory, use a named client for the API and build the session client manually, because the factory shares handlers and their cookie containers between clients.

Each picture costs $0.28 per 1,000 and usually returns under 1 seconds. Unreadable pictures return ERROR_CAPTCHA_UNSOLVABLE at no charge. See Image to Text for all fields.

Suited to your own lookups on registries and portals that allow automated queries, internal RPA and accessibility tooling.

Checking what you send

Before blaming recognition, confirm that the bytes are a picture. GetByteArrayAsync happily returns an HTML error page or a redirect target, which the API cannot read. Check the response's Content.Headers.ContentType when you download with GetAsync, or look at the first bytes: PNG files start with the bytes 137, 80, 78, 71 and JPEG files with 255, 216. While developing, save the bytes with File.WriteAllBytesAsync and open the file to see what the API will receive.

If the picture is tiny or blank, the most likely cause is a lost session: the form and the image were fetched with different cookie containers, or the picture URL was taken from an older page load.

Handling ASP.NET Web Forms targets

Many legacy portals that still use text CAPTCHAs are ASP.NET Web Forms sites. They post back __VIEWSTATE, __VIEWSTATEGENERATOR and __EVENTVALIDATION on every submit, and they reject posts that leave these out. The hidden field dictionary above collects them automatically. If the page uses an update panel, the real submit may be an asynchronous postback with extra headers; copy it from the browser's Network tab in that case.

Batches and pacing

When you run many lookups, process them one session at a time or with a small degree of parallelism using Parallel.ForEachAsync and a MaxDegreeOfParallelism of two or three. Each lookup creates its own session client, downloads its own picture and submits its own answer. Pause briefly between lookups so the target portal is not flooded. Record the task id with each result, and if a site reports a wrong code, retry that lookup once with a new session rather than resubmitting the same picture.

Error handling summary

ERROR_CAPTCHA_UNSOLVABLE and a failed status are free and worth one retry with a new picture. ERROR_ZERO_BALANCE and ERROR_KEY_DENIED_ACCESS stop the batch until a person acts. ERROR_INVALID_TASK_DATA usually means an empty body, which points back at the download step.

Common questions

Does Convert.ToBase64String add a data:image prefix?

No. It returns plain base64, which is what ImageToTextTask expects.

Why one CookieContainer for all three requests?

The expected text is saved in the server side session, so the picture and the submit must carry the same session cookie.

Can I use HtmlAgilityPack instead of AngleSharp?

Yes. Any HTML parser that finds the image src and hidden inputs works.

Why should IHttpClientFactory not hold the session client?

The factory pools and shares handlers, so cookie containers could be shared between lookups. Build session clients yourself.

What if the answer is wrong?

Reload the form for a new picture and solve again. Try the module or score options if it happens often.

Keep reading