.NET Integration
.NET integration patterns with ASP.NET Core middleware, attribute, and Razor tag helper.
Copy these patterns into your project to integrate gkCAPTCHA server-side verification.
Installation
Core Client
terminal
dotnet add package GkCaptchaASP.NET Core Integration
terminal
dotnet add package GkCaptcha.AspNetCoreRequires .NET 8.0 or later.
Quick Start
Program.cs
using GkCaptcha;
var client = new GkCaptchaClient(new GkCaptchaOptions
{
SecretKey = "your_secret_key", // or set GKCAPTCHA_SECRET_KEY env var
SiteKey = "your_site_key", // or set GKCAPTCHA_SITE_KEY env var
});
var result = await client.VerifyTokenAsync(token);
if (result.FailOpen)
{
// API was unreachable - fail-open: request allowed through
Console.WriteLine("Fail-open: allowing request");
}
else if (result.Success)
{
Console.WriteLine($"Human verified (score: {result.Score})");
}
else
{
Console.WriteLine($"Bot detected: {result.Error} ({result.ReasonCode})");
}ASP.NET Core Integration
Dependency Injection
Program.cs
using GkCaptcha.AspNetCore;
builder.Services.AddGkCaptcha(opts =>
{
opts.SecretKey = builder.Configuration["GkCaptcha:SecretKey"];
opts.SiteKey = builder.Configuration["GkCaptcha:SiteKey"];
});Middleware
Protect entire path prefixes. All requests to those paths require a valid CAPTCHA token.
Program.cs
app.UseGkCaptcha(opts =>
{
opts.Paths.Add("/login");
opts.Paths.Add("/register");
});[RequireCaptcha] Attribute
LoginController.cs
using GkCaptcha.AspNetCore;
[HttpPost]
[RequireCaptcha]
public IActionResult Login([FromForm] LoginModel model)
{
// CAPTCHA already verified - proceed with login
return Ok();
}Minimal API
Program.cs
app.MapPost("/api/contact", (ContactRequest req) => Results.Ok())
.RequireGkCaptcha();Razor Tag Helper
Form.cshtml
@* In _ViewImports.cshtml: *@
@addTagHelper *, GkCaptcha.AspNetCore
@* In your Razor view: *@
<form method="post">
<gk-captcha site-key="@Model.SiteKey" theme="dark" />
<button type="submit">Submit</button>
</form>Error Handling
By default (fail-open), if the gkCAPTCHA API is unreachable after 1 retry, the client returns { Success = true, FailOpen = true } — your application continues rather than blocking legitimate users. Set FailClosed = true to throw GkCaptchaException instead.
افتراضيًا (فتح عند الفشل)، إذا كانت واجهة gkCAPTCHA غير متاحة، يُرجع العميل نجاحًا مع علامة FailOpen. لتغيير هذا السلوك استخدم FailClosed = true.
Environment Variables
| Variable | Required | Description |
|---|---|---|
| GKCAPTCHA_SECRET_KEY | Yes | Secret key from gatekeeper.sa dashboard |
| GKCAPTCHA_SITE_KEY | Yes | Site key from gatekeeper.sa dashboard |
| GKCAPTCHA_API_URL | No | Override API URL (default: https://gkcaptcha.gatekeeper.sa) |