开发环境:C#,VS2019,.NET Core 3.1,ASP.NET Core API
1、建立一个验证码控制器
新建两个方法Create和Check,Create用于创建验证码,Check用于验证它是否有效。
声明一个静态类变量存放列表,列表中存放包含令牌和验证码的对象。
private static List _list = new List();
///
/// 返回一个图形验证码和令牌.
///
///
[HttpGet]
public string Create()
{
VCodeCalculateModel model = new VCodeCalculateModel();
model.id = Guid.NewGuid().ToString(); // 生成令牌
var codes = VCodeCalculateModel.GetVCode();
var num1 = codes.Item1;
var num2 = codes.Item2;
var bool_operator = codes.Item3;
if (bool_operator)
{
// 加法运算,生成验证码
model.code = Convert.ToString(num1 + num2);
}
else
{
// 减法运算,生成验证码
model.code = Convert.ToString(num1 - num2);
}
_list.Add(model);
// 返回对象
VCodeCalculateController_Create_Receive result = new VCodeCalculateController_Create_Receive();
result.code = "0";
result.data = new VCodeCalculateController_Create_Receive.Data();
result.data.id = model.id;
var image = VCodeCalculateModel.DrawImage(num1, num2, bool_operator);
var base64 = Utils.BitmapToBase64Str(image);
result.data.img = base64;
var json = JsonConvert.SerializeObject(result);
return json;
}
///
/// 检查验证码是否有效
///
/// 令牌.
/// 验证码.
///
[HttpGet]
public string Check(string id, string code)
{
try
{
var index = _list.FindIndex(m =>
{
if (m.id.Equals(id) && m.code.Equals(code))
{
return true;
}
return false;
});
ReceiveObject result = new ReceiveObject();
if (index >= 0)
{
_list.RemoveAt(index);
result.code = "0";
result.msg = "验证成功";
var json = JsonConvert.SerializeObject(result);
return json;
}
else
{
result.code = "1";
result.msg = "验证失败";
var json = JsonConvert.SerializeObject(result);
return json;
}
}
catch (Exception ex)
{
_logger.LogError(exception: ex, message: ex.Message);
ReceiveObject result = new ReceiveObject();
result.code = "999999";
result.msg = "系统异常";
var json = JsonConvert.SerializeObject(result);
return json;
}
}
2、建立一个验证码模型
验证码模型类包括:令牌和验证码属性。
再创建一个类存放Create方法返回的对象包括:令牌,验证码图片。
创建用于生成2个随机数和运算法的方法。
创建将2个随机数和运算法绘制成图片的方法。
///
/// 令牌.
///
public string id { get; set; }
///
/// 验证码.
///
public string code { get; set; }
///
/// 计算数字列表.
///
static readonly int[] list = new int[50]
{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
};
///
/// 获取随机验证码.
///
/// item1 - 第一个数字,item2 - 第二个数字,item3 - 运算符(true - 加法, false - 减法)
public static Tuple GetVCode()
{
Random random = new Random();
var index = random.Next(0, list.Length);
int num1 = list[index];
var index2 = random.Next(0, list.Length);
int num2 = list[index2];
bool bool_operator = random.Next(0, 2) == 1 ? true : false;
return new Tuple(num1, num2, bool_operator);
}
///
/// 绘制验证码的图片.
///
///
///
public static Bitmap DrawImage(int num1, int num2, bool isAdd)
{
Color[] list_color =
{
Color.FromArgb(240, 230, 140), // 黄褐色(亮)
Color.FromArgb(138, 54, 15), // 黄褐色(暗)
Color.FromArgb(51, 161, 201), // 蓝色(亮)
Color.FromArgb(25, 25, 112), // 蓝色(暗)
Color.FromArgb(192, 192, 192), // 灰白(亮)
Color.FromArgb(128, 128, 105), // 灰白(暗)
};
Random random = new Random();
// 创建画板
Bitmap bitmap = new Bitmap(150, 50);
// 创建画笔
Graphics grp = Graphics.FromImage(bitmap);
grp.Clear(Color.White); // 设置背景色为白色
// 绘制噪点
for (int i = 0; i < random.Next(60, 80); i++)
{
int x = random.Next(bitmap.Width);
int y = random.Next(bitmap.Height);
grp.DrawLine(new Pen(Color.LightGray, 1), x, y, x + 1, y);
}
// 绘制随机的线条
grp.DrawLine(
new Pen(list_color[random.Next(list_color.Length)], random.Next(3)),
new Point(random.Next(bitmap.Width / 2), random.Next(bitmap.Height / 2)),
new Point(bitmap.Width / 2 + random.Next(bitmap.Width / 2), bitmap.Height / 2 + random.Next(bitmap.Height / 2))
);
// 绘制验证码
string code = string.Format("{0}{1}{2}", num1, isAdd ? "+" : "-", num2);
for (int i = 0; i < code.Length; i++)
{
var item = code[i];
grp.DrawString(item.ToString(),
new Font(FontFamily.GenericSansSerif, 25, FontStyle.Bold),
new SolidBrush(list_color[random.Next(list_color.Length)]),
x: (150 / 5) * i,
y: random.Next(5));
}
// 在验证码上绘制噪点
for (int i = 0; i < random.Next(30, 50); i++)
{
int x = random.Next(bitmap.Width);
int y = random.Next(bitmap.Height);
grp.DrawLine(new Pen(list_color[random.Next(list_color.Length)], 1), x, y, x + 1, y);
}
// 绘制随机的线条
grp.DrawLine(
new Pen(list_color[random.Next(list_color.Length)], random.Next(3)),
new Point(random.Next(bitmap.Width / 2), random.Next(bitmap.Height / 2)),
new Point(bitmap.Width / 2 + random.Next(bitmap.Width / 2), bitmap.Height / 2 + random.Next(bitmap.Height / 2))
);
return bitmap;
}
///
/// VCodeCalculateController控制器中Create方法的返回对象.
///
public class VCodeCalculateController_Create_Receive : ReceiveObject
{
public Data data { get; set; }
public class Data
{
///
/// 令牌.
///
public string id { get; set; }
///
/// Base64的验证码图片.
///
public string img { get; set; }
}
}
运行效果: