H2 Diamond.Captcha Class Library
$ dotnet add package Diamond.CaptchaA lightweight and dependency-free Captcha generation package for ASP.NET Core. the Diamond.Captcha generates Captcha images entirely in-memory without relying on any external graphic libraries with zero dependency .
IMemoryCache.The Diamond.Captcha generates the Captcha image dynamically in memory and embeds the corresponding code in either:
CachedCaptcha).DistributedCaptcha).This design eliminates the need for external storage or graphic libraries and supports scalable, secure web applications.
In Program.cs:
AddCachedCaptcha or AddDistributedCaptcha method.using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCachedCaptcha();
//builder.Services.AddDistributedCaptcha(options => options.CryptographyKey = "YOUR_AES_KEY");
var app = builder.Build();
app.Run();
In HomeController.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Html;
using Diamond.AspNetCore.Html.Captcha;
public class HomeController : Controller
{
private readonly ICachedCaptcha m_Captcha;
public HomeController(ICachedCaptcha captcha)
{
this.m_Captcha = captcha;
}
[HttpGet]
public IActionResult Index()
{
return this.View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(string Captcha_RefID, string Input_Captcha)
{
if (this.m_Captcha.Validate(Captcha_RefID, Input_Captcha))
{
return this.Ok("Captcha validated successfully");
}
else
{
return this.BadRequest("Invalid Captcha");
}
}
public IActionResult CaptchaImage(string id, int version = 0)
{
return this.m_Captcha.GetImage(id, version);
}
}
In Index.cshtml:
@inject Diamond.AspNetCore.Html.Captcha.ICachedCaptcha captcha
@{
string captchaRefID = captcha.NewRefID();
}
<form asp-antiforgery="true">
<input type="hidden" id="Captcha_RefID" name="Captcha_RefID" value="@captchaRefID" />
<input type="text" name="Input_Captcha" autocomplete="off" autocorrect="off" />
<img id="CaptchaImage" src="/Home/CaptchaImage/@captchaRefID" />
<a href="#" onclick="OnCaptchaRefresh()">Refresh</a>
<script language="javascript">
var version = 0;
function OnCaptchaRefresh()
{
version++;
var img = document.getElementById("CaptchaImage");
img.src = "/Home/CaptchaImage/@captchaRefID?version=" + version;
return false;
}
</script>
</form>