C#验证码使用

时间:2023-11-14 20:47:02

1、C#创建验证码

1.1 创建获取验证码页面(ValidateCode.aspx)

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3. <title>获取验证码</title>
  4. </head>
  5. <body>
  6. <form id="form1" runat="server">
  7. <div>获取验证码</div>
  8. </form>
  9. </body>
  10. </html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>获取验证码</title>
</head>
<body>
<form id="form1" runat="server">
<div>获取验证码</div>
</form>
</body>
</html>


1.2 编写获取验证码代码(ValidateCode.aspx.cs)

  1. /// <summary>
  2. /// 验证码类型(0-字母数字混合,1-数字,2-字母)
  3. /// </summary>
  4. private string validateCodeType = "0";
  5. /// <summary>
  6. /// 验证码字符个数
  7. /// </summary>
  8. private int validateCodeCount = 4;
  9. /// <summary>
  10. /// 验证码的字符集,去掉了一些容易混淆的字符
  11. /// </summary>
  12. char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
  13. protected void Page_Load(object sender, EventArgs e)
  14. {
  15. //取消缓存
  16. Response.BufferOutput = true;
  17. Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
  18. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
  19. Response.AppendHeader("Pragma", "No-Cache");
  20. //获取设置参数
  21. if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
  22. {
  23. validateCodeType = Request.QueryString["validateCodeType"];
  24. }
  25. if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
  26. {
  27. int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
  28. }
  29. //生成验证码
  30. this.CreateCheckCodeImage(GenerateCheckCode());
  31. }
  32. private string GenerateCheckCode()
  33. {
  34. char code ;
  35. string checkCode = String.Empty;
  36. System.Random random = new Random();
  37. for (int i = 0; i < validateCodeCount; i++)
  38. {
  39. code = character[random.Next(character.Length)];
  40. // 要求全为数字或字母
  41. if (validateCodeType == "1")
  42. {
  43. if ((int)code < 48 || (int)code > 57)
  44. {
  45. i--;
  46. continue;
  47. }
  48. }
  49. else if (validateCodeType == "2")
  50. {
  51. if ((int)code < 65 || (int)code > 90)
  52. {
  53. i--;
  54. continue;
  55. }
  56. }
  57. checkCode += code;
  58. }
  59. Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
  60. this.Session["CheckCode"] = checkCode;
  61. return checkCode;
  62. }
  63. private void CreateCheckCodeImage(string checkCode)
  64. {
  65. if (checkCode == null || checkCode.Trim() == String.Empty)
  66. return;
  67. System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*15.0+40)), 23);
  68. System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  69. try
  70. {
  71. //生成随机生成器
  72. Random random = new Random();
  73. //清空图片背景色
  74. g.Clear(System.Drawing.Color.White);
  75. //画图片的背景噪音线
  76. for (int i = 0; i < 25; i++)
  77. {
  78. int x1 = random.Next(image.Width);
  79. int x2 = random.Next(image.Width);
  80. int y1 = random.Next(image.Height);
  81. int y2 = random.Next(image.Height);
  82. g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
  83. }
  84. System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
  85. System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
  86. int cySpace = 16;
  87. for (int i = 0; i < validateCodeCount; i++)
  88. {
  89. g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
  90. }
  91. //画图片的前景噪音点
  92. for (int i = 0; i < 100; i++)
  93. {
  94. int x = random.Next(image.Width);
  95. int y = random.Next(image.Height);
  96. image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
  97. }
  98. //画图片的边框线
  99. g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
  100. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  101. image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
  102. Response.ClearContent();
  103. Response.ContentType = "image/Gif";
  104. Response.BinaryWrite(ms.ToArray());
  105. }
  106. finally
  107. {
  108. g.Dispose();
  109. image.Dispose();
  110. }
  111. }
/// <summary>
/// 验证码类型(0-字母数字混合,1-数字,2-字母)
/// </summary>
private string validateCodeType = "0";
/// <summary>
/// 验证码字符个数
/// </summary>
private int validateCodeCount = 4;
/// <summary>
/// 验证码的字符集,去掉了一些容易混淆的字符
/// </summary>
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' }; protected void Page_Load(object sender, EventArgs e)
{
//取消缓存
Response.BufferOutput = true;
Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.AppendHeader("Pragma", "No-Cache");
//获取设置参数
if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
{
validateCodeType = Request.QueryString["validateCodeType"];
}
if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
{
int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
}
//生成验证码
this.CreateCheckCodeImage(GenerateCheckCode());
} private string GenerateCheckCode()
{
char code ;
string checkCode = String.Empty;
System.Random random = new Random(); for (int i = 0; i < validateCodeCount; i++)
{
code = character[random.Next(character.Length)]; // 要求全为数字或字母
if (validateCodeType == "1")
{
if ((int)code < 48 || (int)code > 57)
{
i--;
continue;
}
}
else if (validateCodeType == "2")
{
if ((int)code < 65 || (int)code > 90)
{
i--;
continue;
}
}
checkCode += code;
} Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
this.Session["CheckCode"] = checkCode;
return checkCode;
} private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return; System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*15.0+40)), 23);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); try
{
//生成随机生成器
Random random = new Random(); //清空图片背景色
g.Clear(System.Drawing.Color.White); //画图片的背景噪音线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height); g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
} System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true); int cySpace = 16;
for (int i = 0; i < validateCodeCount; i++)
{
g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
} //画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height); image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
} //画图片的边框线
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}

2、验证码的使用

2.1 验证码的前段显示代码

  1. <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
<img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">

2.2 创建验证码测试页面(ValidateTest.aspx)

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3. <title>验证码测试</title>
  4. </head>
  5. <body>
  6. <form id="form1" runat="server">
  7. <div>
  8. <input runat="server" id="txtValidate" />
  9. <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
  10. <asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click"  />
  11. </div>
  12. </form>
  13. </body>
  14. </html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>验证码测试</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input runat="server" id="txtValidate" />
<img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
<asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click" />
</div>
</form>
</body>
</html>

2.3 编写验证码测试的提交代码(ValidateTest.aspx.cs)

  1. protected void btnVal_Click(object sender, EventArgs e)
  2. {
  3. bool result = false;   //验证结果
  4. string userCode = this.txtValidate.Value; //获取用户输入的验证码
  5. if (String.IsNullOrEmpty(userCode))
  6. {
  7. //请输入验证码
  8. return;
  9. }
  10. string validCode = this.Session["CheckCode"] as String;  //获取系统生成的验证码
  11. if (!string.IsNullOrEmpty(validCode))
  12. {
  13. if (userCode.ToLower() == validCode.ToLower())
  14. {
  15. //验证成功
  16. result = true;
  17. }
  18. else
  19. {
  20. //验证失败
  21. result = false;
  22. }
  23. }
  24. }