AntiCaptchaApi.Net
AntiCaptchaApi.Net provides a convenient wrapper around the Anti-captcha API methods, allowing you to easily integrate captcha solving capabilities into your .NET applications. It supports various captcha types and provides options for configuration and error handling.
Install / Use
/learn @Remarkable-Solutions/AntiCaptchaApi.NetREADME
AntiCaptchaApi.Net 
A .NET 9 library that implements the anti-captcha.com API.
AntiCaptchaApi.Net provides a convenient wrapper around the Anti-captcha API methods, allowing you to easily integrate captcha solving capabilities into your .NET applications. It supports various captcha types and provides options for configuration and error handling.
Features
- Supports multiple captcha types (ImageToText, Recaptcha V2/V3/Enterprise, HCaptcha, FunCaptcha, GeeTest, Turnstile, etc.)
- Async methods for non-blocking operations.
- Configuration options for timeouts, retries, and polling intervals.
- Dependency Injection support for easy integration.
- Proxy support for relevant task types.
- Task reporting capabilities.
Installation
You can install the package via the .NET CLI or the NuGet Package Manager Console.
.NET CLI
dotnet add package AntiCaptchaApi.Net
Package Manager Console
Install-Package AntiCaptchaApi.Net
Migration Guide (From Older Versions)
This library primarily uses IHttpClientFactory for robust and efficient management of HttpClient instances, integrated via Dependency Injection (DI). While manual instantiation of AnticaptchaClient is now supported again, the DI approach is still recommended for most scenarios due to its benefits.
Why use IHttpClientFactory (Recommended Approach)?
Using IHttpClientFactory provides several benefits:
- Improved Performance: Addresses issues like socket exhaustion that can occur with direct
HttpClientinstantiation and disposal. - Centralized Configuration: Allows for configuring
HttpClientinstances (e.g., default headers, Polly policies for resilience) in a central place. - Simplified Lifetime Management:
IHttpClientFactorymanages the lifetime ofHttpClientMessageHandlerinstances, optimizing resource use.
How to Use Dependency Injection (Recommended):
- Ensure you have the
Microsoft.Extensions.Httppackage referenced (usually included with ASP.NET Core or available as a separate NuGet package). TheAddAnticaptchamethod will callservices.AddHttpClient()for you. - Register
IAnticaptchaClientusing theAddAnticaptchaextension method in yourConfigureServicesmethod (e.g., inStartup.csorProgram.cs).
// In your service configuration (e.g., Startup.cs or Program.cs)
services.AddAnticaptcha("YOUR_API_KEY", options => {
// Optional: configure client options
options.MaxWaitForTaskResultTimeMs = 180000;
});
// In your service/controller
public class MyService
{
private readonly IAnticaptchaClient _anticaptchaClient;
public MyService(IAnticaptchaClient anticaptchaClient)
{
_anticaptchaClient = anticaptchaClient;
}
// ... use _anticaptchaClient
}
How to Use Manual Instantiation (Alternative Approach):
Manual instantiation is now supported via a public constructor. You can optionally provide your own HttpClient instance for more control over its configuration.
// Basic manual instantiation
var client = new AnticaptchaClient("YOUR_API_KEY");
// Manual instantiation with custom ClientConfig
var config = new ClientConfig { MaxWaitForTaskResultTimeMs = 120000 };
var clientWithConfig = new AnticaptchaClient("YOUR_API_KEY", config);
// Manual instantiation with custom HttpClient and ClientConfig
var customHttpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
var clientWithCustomHttpClient = new AnticaptchaClient("YOUR_API_KEY", config, customHttpClient);
Configuration
The client behavior can be customized using ClientConfig.
Using Dependency Injection (Required):
The only way to obtain and configure an IAnticaptchaClient instance is through service registration using the AddAnticaptcha extension method. This ensures proper HttpClient management via IHttpClientFactory.
using AntiCaptchaApi.Net;
using Microsoft.Extensions.DependencyInjection;
public void ConfigureServices(IServiceCollection services)
{
// Add other services...
string antiCaptchaApiKey = "YOUR_API_KEY"; // Replace with your actual API key
services.AddAnticaptcha(antiCaptchaApiKey, options =>
{
// Customize client configuration (optional)
options.MaxWaitForTaskResultTimeMs = 180000; // Wait up to 3 minutes for task result
options.DelayTimeBetweenCheckingTaskResultMs = 5000; // Poll every 5 seconds
options.SolveAsyncRetries = 2; // Retry once on solvable errors
});
// Add other services...
}
Basic Usage (with Dependency Injection)
- Register the client in your
Startup.csorProgram.csas shown in the Configuration section. - Inject
IAnticaptchaClientinto your service/controller. - Create a request object for the desired captcha type.
- Call
SolveCaptchaAsyncto get the solution.
Example: Solving an ImageToText Captcha
using AntiCaptchaApi.Net;
using AntiCaptchaApi.Net.Enums;
using AntiCaptchaApi.Net.Models.Solutions;
using AntiCaptchaApi.Net.Requests;
using System;
using System.Threading.Tasks;
public class MyCaptchaService
{
private readonly IAnticaptchaClient _anticaptchaClient;
public MyCaptchaService(IAnticaptchaClient anticaptchaClient)
{
_anticaptchaClient = anticaptchaClient;
}
public async Task<string> SolveImageCaptchaAsync(string imageFilePath)
{
var request = new ImageToTextRequest
{
FilePath = imageFilePath, // Loads image from path into BodyBase64
// Optional parameters:
// Phrase = false,
// Case = true,
// Numeric = NumericOption.NumbersOnly,
// MinLength = 4,
// MaxLength = 6
};
try
{
// Solve the captcha (creates task and waits for result)
var result = await _anticaptchaClient.SolveCaptchaAsync(request);
if (result.Status == TaskStatusType.Ready)
{
Console.WriteLine($"Captcha solved successfully! Solution: {result.Solution.Text}");
return result.Solution.Text;
}
else
{
Console.WriteLine($"Captcha solving failed. Error: {result.ErrorCode} - {result.ErrorDescription}");
// Optionally report incorrect solution if applicable (though less common for ImageToText)
// await _anticaptchaClient.ReportTaskOutcomeAsync(result.CreateTaskResponse.TaskId.Value, ReportOutcome.IncorrectImageCaptcha);
return null;
}
}
catch (Exception ex)
{
Console.WriteLine($"An exception occurred: {ex.Message}");
return null;
}
}
}
Alternative: Two-Step Solving
You can also create the task and poll for the result manually.
// 1. Create the task
var createTaskResponse = await _anticaptchaClient.CreateCaptchaTaskAsync(request);
if (createTaskResponse.IsErrorResponse || !createTaskResponse.TaskId.HasValue)
{
Console.WriteLine($"Failed to create task: {createTaskResponse.ErrorCode} - {createTaskResponse.ErrorDescription}");
return;
}
Console.WriteLine($"Task created with ID: {createTaskResponse.TaskId.Value}");
// 2. Wait for the result (polls the API)
var taskResult = await _anticaptchaClient.WaitForTaskResultAsync<ImageToTextSolution>(createTaskResponse.TaskId.Value);
if (taskResult.Status == TaskStatusType.Ready)
{
Console.WriteLine($"Captcha solved! Solution: {taskResult.Solution.Text}");
}
else
{
Console.WriteLine($"Task failed: {taskResult.ErrorCode} - {taskResult.ErrorDescription}");
}
API Client Methods
Here's an overview of the methods available on IAnticaptchaClient:
Task<BalanceResponse> GetBalanceAsync(CancellationToken cancellationToken): Docsvar balanceResponse = await client.GetBalanceAsync(); Console.WriteLine($"Current Balance: {balanceResponse.Balance}");Task<CreateTaskResponse> CreateCaptchaTaskAsync<T>(ICaptchaRequest<T> request, ...): Docs// See Two-Step Solving example aboveTask<TaskResultResponse<TSolution>> GetTaskResultAsync<TSolution>(int taskId, CancellationToken cancellationToken): Docs// Checks task status once, might still be processing var result = await client.GetTaskResultAsync<ImageToTextSolution>(taskId);Task<TaskResultResponse<TSolution>> WaitForTaskResultAsync<TSolution>(int taskId, ...): (UsesgetTaskResultinternally with polling)// See Two-Step Solving example aboveTask<TaskResultResponse<TSolution>> SolveCaptchaAsync<TSolution>(ICaptchaRequest<TSolution> request, ...): (CombinesCreateCaptchaTaskAsyncandWaitForTaskResultAsync)// See Basic Usage example aboveTask<GetQueueStatsResponse> GetQueueStatsAsync(QueueType queueType, ...): Docsvar stats = await client.GetQueueStatsAsync(QueueType.RecaptchaV2Proxyless);Task<GetSpendingStatsResponse> GetSpendingStatsAsync(...): Docsvar spending = await client.GetSpendingStatsAsync(queue: "ImageToTextTask");Task<GetAppStatsResponse> GetAppStatsAsync(int softId, ...): Docs// Replace 123 with your actual SoftID var appStats = await client.GetAppStatsAsync(123
