C# 实现图片验证码的 WebAPI 版(ASP.NET Core)

简介: 基于ASP.NET Core实现的验证码服务,生成带干扰线和随机旋转文字的4位图文验证码,支持内存存储与验证。需安装System.Drawing.Common包。

using Microsoft.AspNetCore.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

[ApiController]
[Route("api/[controller]")]
public class CaptchaController : ControllerBase
{
// 存储验证码的内存缓存(生产环境建议用分布式缓存)
private static readonly ConcurrentDictionary _captchaStore = new();

// 获取验证码图片
[HttpGet("image/{token}")]
public IActionResult GetCaptchaImage(string token, int width = 120, int height = 40)
{
    // 生成4位数字+字母验证码
    var captchaCode = GenerateRandomCode(4);
    _captchaStore[token] = captchaCode;

    // 创建位图
    using var bitmap = new Bitmap(width, height);
    using var g = Graphics.FromImage(bitmap);
    // 设置背景色
    g.Clear(Color.White);

    // 绘制干扰线
    var random = new Random();
    for (int i = 0; i < 5; i++)
    {
        using var pen = new Pen(Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)), 1);
        g.DrawLine(pen, random.Next(width), random.Next(height), random.Next(width), random.Next(height));
    }

    // 绘制验证码文字
    using var font = new Font("Arial", 18, FontStyle.Bold | FontStyle.Italic);
    for (int i = 0; i < captchaCode.Length; i++)
    {
        using var brush = new SolidBrush(Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)));
        // 文字随机偏移和旋转
        var x = 10 + i * 25;
        var y = random.Next(5, 15);
        g.RotateTransform(random.Next(-15, 15));
        g.DrawString(captchaCode[i].ToString(), font, brush, x, y);
        g.ResetTransform();
    }

    // 绘制干扰点
    for (int i = 0; i < 200; i++)
    {
        bitmap.SetPixel(random.Next(width), random.Next(height), Color.FromArgb(random.Next(256)));
    }

    // 输出图片流
    using var ms = new MemoryStream();
    bitmap.Save(ms, ImageFormat.Png);
    return File(ms.ToArray(), "image/png");
}

// 验证验证码
[HttpPost("verify/{token}")]
public IActionResult VerifyCaptcha(string token, [FromBody] string inputCode)
{
    if (_captchaStore.TryGetValue(token, out var realCode))
    {
        _captchaStore.TryRemove(token, out _); // 验证后立即失效
        if (string.Equals(realCode, inputCode, StringComparison.OrdinalIgnoreCase))
        {
            return Ok(new { Success = true, Message = "验证通过" });
        }
    }
    return Ok(new { Success = false, Message = "验证码错误或已过期" });
}

// 生成随机验证码
private string GenerateRandomCode(int length)
{
    var chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 排除易混淆字符
    var random = new Random();
    var code = new char[length];
    for (int i = 0; i < length; i++)
    {
        code[i] = chars[random.Next(chars.Length)];
    }
    return new string(code);
}

}
注意:ASP.NET Core 项目需安装System.Drawing.Common NuGet 包。

相关文章
|
2天前
|
C#
C# 利用特性(Attribute)实现自定义验证
通过自定义特性(如RequiredAttribute)标记类属性,利用反射实现数据验证逻辑。示例代码展示了如何在对象中检查必填字段,并输出验证错误信息,实现灵活的数据校验机制。
|
1天前
|
云安全 人工智能 安全
阿里云2026云上安全健康体检正式开启
新年启程,来为云上环境做一次“深度体检”
1470 6
|
2天前
|
安全 测试技术 Linux
Acunetix v25.12.5 发布,新增功能简介
Acunetix v25.12.5 (Linux, Windows) - Web 应用程序安全测试
35 0
Acunetix v25.12.5 发布,新增功能简介
|
2天前
|
存储 缓存 安全
C# 实现带过期时间的本地缓存工具
基于ConcurrentDictionary与定时清理机制,实现线程安全的本地缓存,支持键值过期自动清除。每分钟扫描并移除过期项,有效防止内存溢出,适用于需短暂存储数据的场景,如用户会话、临时配置等,保障性能与稳定性。
|
2天前
|
存储 安全 C#
C# 数组与集合:List<T> 最常用场景
数组长度固定,集合(List&lt;T&gt;)可动态增删,支持泛型与类型安全。常用操作包括添加、删除、遍历和查询元素,是开发中首选的动态数据存储方式。
|
2天前
|
存储 C#
C# 实现简单的备忘录模式
备忘录模式在不破坏封装性的前提下,捕获并保存对象的内部状态,以便后续恢复。通过原发器创建备忘录,管理者存储备忘录,可实现状态回滚。
|
2天前
|
C#
C# 实现简单的 Excel 数据写入工具
基于EPPlus库实现C#将数据写入Excel文件,支持自定义表头与多行数据,自动调整列宽,操作简便,适用于非商业场景的数据导出需求。
|
2天前
|
C# 索引
C# 循环结构:for/foreach/while 效率对比
循环用于重复执行代码,根据场景选择:for 适合已知次数,foreach 简洁遍历集合,while 适用于条件控制。示例演示遍历商品价格列表并计算总和,展示三种循环的用法与差异。(239字)
|
2天前
|
安全 C#
C# 实现简单的单例模式(懒汉式)
单例模式确保一个类仅存在一个实例,并提供全局访问点。通过私有构造函数防止外部实例化,结合静态属性和延迟初始化实现线程安全的唯一实例,常用于日志、配置管理等场景。
|
2天前
|
C#
C# 条件判断:if-else 与 switch 的实用场景
条件判断是流程控制的核心。if-else适用于多级条件判断,如根据积分决定会员等级;switch适用于多值匹配,C# 7.0+支持字符串和数值匹配,可清晰处理会员等级对应的优惠策略。

热门文章

最新文章