C# captcha solver: a .NET API client with HttpClient

A C# captcha solver is a short .NET program that posts a challenge to a solver API and reads the answer with HttpClient and System.Text.Json, both included in .NET 6 or newer. With ilovecaptcha it makes two HTTPS calls, createTask then getTaskResult, written as asynchronous methods. This page explains the request, the image, the wait and the errors, then gives the complete Program.cs.

Updated on · Written and maintained by the ilovecaptcha team

Preview: the API described here is in public beta. Endpoint names, fields and codes can still change until the end of the beta, and no API key is distributed yet.

How do you call a captcha solver API from C#?

With HttpClient and the JSON types of System.Text.Json.Nodes. The method Post adds the key to a JsonObject under clientKey, sends it with PostAsJsonAsync, which serialises the body and sets the content type, then reads the reply as a JsonNode with ReadFromJsonAsync. One HttpClient serves the whole program, with a Timeout of 30 seconds.

The C# example at a glance
Item Value
Runs on .NET 6 or newer
Packages to add None: base class library only
File Program.cs
Create and run dotnet new console -o solve && copy Program.cs solve && cd solve && dotnet run
HTTP client HttpClient

How do you send the captcha image and wait for the answer in C#?

File.ReadAllBytesAsync loads the image and Convert.ToBase64String encodes it. Solve posts the task to createTask, reads taskId, then awaits Task.Delay before each call to getTaskResult, until status is ready.

  • pollInterval is a TimeSpan of 1.5 seconds.
  • maxWait is a TimeSpan of 120 seconds: past that, Solve throws a TimeoutException.
  • taskId is read as a long, so the example expects a numeric identifier.
  • A reply already ready at createTask is returned at once.

How do you handle the API key and errors in C#?

Read the key with Environment.GetEnvironmentVariable from a variable such as ILOVECAPTCHA_KEY, or from the user secrets of the project, instead of the constant ApiKey. When errorId is present and not 0, Post throws an InvalidOperationException with errorCode and errorDescription; an empty reply throws the same type. A network failure surfaces as an HttpRequestException, and a request that exceeds the timeout as a TaskCanceledException: catch both around Solve.

What does a complete C# captcha solver client look like?

The file below is the whole client, in 45 lines. It uses top-level statements, so there is no class and no Main to declare: it defines the local functions Post, Solve and GetBalance, then reads captcha.png, submits it as an aws-waf task and prints the solution. Replace YOUR_API_KEY and YOUR_API_URL with your own values before you run it.

Program.cs · Complete C# client: one createTask call, then getTaskResult until the task is ready (preview format).
using System.Net.Http.Json;
using System.Text.Json.Nodes;

const string ApiKey = "YOUR_API_KEY";
const string BaseUrl = "YOUR_API_URL";
var pollInterval = TimeSpan.FromSeconds(1.5);
var maxWait = TimeSpan.FromSeconds(120);
var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };

async Task<JsonNode> Post(string route, JsonObject body)
{
    body["clientKey"] = ApiKey;
    using var response = await http.PostAsJsonAsync(BaseUrl + route, body);
    var result = await response.Content.ReadFromJsonAsync<JsonNode>() ?? throw new InvalidOperationException("empty response");
    if ((int?)result["errorId"] is int errorId && errorId != 0)
    {
        throw new InvalidOperationException($"{result["errorCode"]}: {result["errorDescription"]}");
    }
    return result;
}

async Task<JsonNode> Solve(JsonObject task)
{
    var result = await Post("/createTask", new JsonObject { ["task"] = task });
    if ((string?)result["status"] == "ready") return result["solution"]!;
    var taskId = (long)result["taskId"]!;
    var deadline = DateTime.UtcNow + maxWait;
    while (DateTime.UtcNow < deadline)
    {
        await Task.Delay(pollInterval);
        result = await Post("/getTaskResult", new JsonObject { ["taskId"] = taskId });
        if ((string?)result["status"] == "ready") return result["solution"]!;
    }
    throw new TimeoutException($"task {taskId} not ready after {maxWait.TotalSeconds} s");
}

async Task<decimal> GetBalance()
{
    var result = await Post("/getBalance", new JsonObject());
    return (decimal)result["balance"]!;
}

var image = Convert.ToBase64String(await File.ReadAllBytesAsync("captcha.png"));
Console.WriteLine(await Solve(new JsonObject { ["type"] = "aws-waf", ["image"] = image }));
Console.WriteLine(await GetBalance());

C# captcha solver: frequently asked questions

Do I need a NuGet package or an SDK to solve captchas in C#?

No. HttpClient, the PostAsJsonAsync extension and JsonNode are part of .NET 6 or newer: the project file created by dotnet new console needs no PackageReference. The file on this page is the complete client. In a larger application, move Post and Solve into a class and receive the HttpClient from IHttpClientFactory, which manages its connections for you.

Does the C# example run on .NET Framework?

Not as written. It relies on top-level statements, on System.Net.Http.Json and on System.Text.Json.Nodes, which arrived with .NET 5 and .NET 6. On .NET Framework 4.8, wrap the code in a class with a Main method and replace the JSON types with a library such as Newtonsoft.Json; HttpClient itself exists there, with PostAsync and a StringContent body. The two calls and the loop stay the same.

What does Solve return in C#, and how do you read it?

A JsonNode: the solution object of the API. Index it with the key your task type returns and cast the value: a string for token or text, a number for offset. For points, call AsArray and read each pair as two integers, in pixels of the image you submitted. In a larger program, turn the node into a record with the Deserialize method, to get typed properties instead of string keys.

Sources

The facts and figures quoted on this page come from these sources.