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.
- 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.
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
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
HttpClient
instantiation and disposal. - Centralized Configuration: Allows for configuring
HttpClient
instances (e.g., default headers, Polly policies for resilience) in a central place. - Simplified Lifetime Management:
IHttpClientFactory
manages the lifetime ofHttpClientMessageHandler
instances, optimizing resource use.
How to Use Dependency Injection (Recommended):
- Ensure you have the
Microsoft.Extensions.Http
package referenced (usually included with ASP.NET Core or available as a separate NuGet package). TheAddAnticaptcha
method will callservices.AddHttpClient()
for you. - Register
IAnticaptchaClient
using theAddAnticaptcha
extension method in yourConfigureServices
method (e.g., inStartup.cs
orProgram.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);
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...
}
- Register the client in your
Startup.cs
orProgram.cs
as shown in the Configuration section. - Inject
IAnticaptchaClient
into your service/controller. - Create a request object for the desired captcha type.
- Call
SolveCaptchaAsync
to 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}");
}
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 above
Task<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, ...)
: (UsesgetTaskResult
internally with polling)// See Two-Step Solving example above
Task<TaskResultResponse<TSolution>> SolveCaptchaAsync<TSolution>(ICaptchaRequest<TSolution> request, ...)
: (CombinesCreateCaptchaTaskAsync
andWaitForTaskResultAsync
)// See Basic Usage example above
Task<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, AppStatsMode.Errors);
Task<ActionResponse> ReportTaskOutcomeAsync(int taskId, ReportOutcome outcome, ...)
: Docs for reporting (Note: Method names vary in API docs, this library uses a single method)// Example: Report an incorrectly solved Recaptcha if (taskResult.Status == TaskStatusType.Ready /* but solution was wrong */) { await client.ReportTaskOutcomeAsync(taskId, ReportOutcome.IncorrectRecaptcha); }
Task<ActionResponse> PushAntiGateVariableAsync(int taskId, string name, object value, ...)
: Docs (For AntiGate custom tasks)// await client.PushAntiGateVariableAsync(taskId, "varName", "varValue");
2.1.3
- Added Amazon WAF captcha support (AmazonTaskProxyless and AmazonTask).
- Clone the repository:
git clone https://github.com/RemarkableSolutionsAdmin/AntiCaptchaApi.Net.git
- Create a new branch for your feature or bug fix.
- Make your changes.
- Ensure tests pass (add new tests if applicable).
- Push your branch to your fork.
- Create a Pull Request.
MIT - see the LICENSE file for details.
Copyright (c) 2022-2025 Remarkable Solutions