首页 .NET/Web Vue3+NETAPI实现验证码 captchaKey,captchaBase64

Vue3+NETAPI实现验证码 captchaKey,captchaBase64

作者:胡同里的砖头 围观群众:88 更新于:2024-09-29

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

public class CaptchaHelper
{
public (string key, string base64) GenerateCaptcha()
{
string key = Guid.NewGuid().ToString("N"); // 生成一个唯一的Key
string captchaText = GenerateRandomCode(4); // 生成一个4位随机验证码

Bitmap bitmap = new Bitmap(100, 30);
Graphics graphic = Graphics.FromImage(bitmap);

try
{
var rnd = new Random();
// 设置验证码的字体、颜色等属性
Random random = new Random();
Font font = new Font("Arial", 15, FontStyle.Bold);
Brush brush = new SolidBrush(Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
PointF point = new PointF(5, 5);

// 绘制验证码
graphic.Clear(Color.White);
graphic.DrawString(captchaText, font, brush, point);

// 将图片转换为Base64字符串
using (MemoryStream memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream, ImageFormat.Png);
byte[] imageBytes = memoryStream.ToArray();

string base64String = Convert.ToBase64String(imageBytes);
return (key, base64String);
}
}
finally
{
graphic.Dispose();
bitmap.Dispose();
}
}

private string GenerateRandomCode(int length)
{
const string randomCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();

for (int i = 0; i < length; i++)
{
sb.Append(randomCode[random.Next(randomCode.Length)]);
}

return sb.ToString();
}
}

控制器

[HttpGet]
public async Task<IActionResult> Captcha()
{
(string key, string base64) =new CaptchaHelper().GenerateCaptcha();
return Ok(new
{
code,
data =
new
{
captchaKey = key,
captchaBase64 = "data:image/png;base64,"+ base64
}
});
}
Vue前端
/** 获取验证码 */
function getCaptcha() {
AuthAPI.getCaptcha().then((data) => {
loginData.value.captchaKey = data.captchaKey;
captchaBase64.value = data.captchaBase64;
});
}
<el-image
@click="getCaptcha"
:src="captchaBase64"
class="captcha-image"
/>
实现效果:

  • 本文标题: Vue3+NETAPI实现验证码 captchaKey,captchaBase64
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8