查看: 2097|回复: 0

[.NET开发] ASP.NET实现的生成验证码功能示例【附demo源码】

发表于 2018-1-2 08:00:00

本文实例讲述了asp.net实现的生成验证码功能。分享给大家供大家参考,具体如下:

生成验证码原理:产生随机字符,并将字符生成为图片,同时储存到Session里去,然后验证用户输入的内容是否与Session中的验证码相符即可。

效果图:用户可以点击切换验证码信息。

一般处理程序:CheckCodeHandler.cs

  1. <%@ WebHandler Language="C#" Class="CheckCodeHandler" %>
  2. using System;
  3. using System.Web;
  4. using System.Text;
  5. using System.Drawing;
  6. using System.Web.SessionState;
  7. public class CheckCodeHandler : IHttpHandler,IRequiresSessionState
  8. {
  9. //产生验证码的字符集
  10. public string charcode = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y";
  11. public void ProcessRequest (HttpContext context) {
  12. string validateCode = CreateRandomCode(4);
  13. context.Session["ValidateCode"] = validateCode;//将验证码保存到session中
  14. CreateCodeImage(validateCode, context);
  15. }
  16. public bool IsReusable {
  17. get {
  18. return false;
  19. }
  20. }
  21. /// <summary>
  22. /// 生成验证码
  23. /// </summary>
  24. /// <param name="n">验证码个数</param>
  25. /// <returns>验证码字符串</returns>
  26. public string CreateRandomCode(int n)
  27. {
  28. string[] CharArray = charcode.Split(',');//将字符串转换为字符数组
  29. string randomCode = "";
  30. int temp = -1;
  31. Random rand = new Random();
  32. for (int i = 0; i < n; i++)
  33. {
  34. if (temp != -1)
  35. {
  36. rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
  37. }
  38. int t = rand.Next(CharArray.Length - 1);
  39. if (temp != -1 && temp == t)
  40. {
  41. return CreateRandomCode(n);
  42. }
  43. temp = t;
  44. randomCode += CharArray[t];
  45. }
  46. return randomCode;
  47. }
  48. public void CreateCodeImage(string checkCode, HttpContext context)
  49. {
  50. int iwidth = (int)(checkCode.Length * 13);
  51. System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
  52. Graphics g = Graphics.FromImage(image);
  53. Font f = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold));
  54. // 前景色
  55. Brush b = new System.Drawing.SolidBrush(Color.Black);
  56. // 背景色
  57. g.Clear(Color.White);
  58. // 填充文字
  59. g.DrawString(checkCode, f, b, 0, 1);
  60. // 随机线条
  61. Pen linePen = new Pen(Color.Gray, 0);
  62. Random rand = new Random();
  63. for (int i = 0; i < 5; i++)
  64. {
  65. int x1 = rand.Next(image.Width);
  66. int y1 = rand.Next(image.Height);
  67. int x2 = rand.Next(image.Width);
  68. int y2 = rand.Next(image.Height);
  69. g.DrawLine(linePen, x1, y1, x2, y2);
  70. }
  71. // 随机点
  72. for (int i = 0; i < 30; i++)
  73. {
  74. int x = rand.Next(image.Width);
  75. int y = rand.Next(image.Height);
  76. image.SetPixel(x, y, Color.Gray);
  77. }
  78. // 边框
  79. g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);
  80. // 输出图片
  81. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  82. image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  83. context.Response.ClearContent();
  84. context.Response.ContentType = "image/jpeg";
  85. context.Response.BinaryWrite(ms.ToArray());
  86. g.Dispose();
  87. image.Dispose();
  88. }
  89. }
复制代码

封装成类库:ValidateNumber.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Drawing;
  6. using System.Web.UI;
  7. using System.Drawing.Drawing2D;
  8. using System.IO;
  9. using System.Drawing.Imaging;
  10. /// <summary>
  11. ///ValidateNumber 生成验证码
  12. /// </summary>
  13. public class ValidateNumber
  14. {
  15. //产生验证码的字符集 (易混淆的字符去掉)
  16. private string charcode = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y";
  17. /// <summary>
  18. /// 验证码的最大长度
  19. /// </summary>
  20. public int MaxLength
  21. {
  22. get { return 10; }
  23. }
  24. /// <summary>
  25. /// 验证码的最小长度
  26. /// </summary>
  27. public int MinLength
  28. {
  29. get { return 1; }
  30. }
  31. /// <summary>
  32. /// 生成验证码
  33. /// </summary>
  34. /// <param name="length">指定验证码的长度</param>
  35. /// <returns></returns>
  36. public string CreateValidateNumber(int length)
  37. {
  38. string[] CharArray = charcode.Split(',');//将字符串转换为字符数组
  39. string randomCode = "";
  40. int temp = -1;
  41. Random rand = new Random();
  42. for (int i = 0; i < length; i++)
  43. {
  44. if (temp != -1)
  45. {
  46. rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
  47. }
  48. int t = rand.Next(CharArray.Length - 1);
  49. if (temp != -1 && temp == t)
  50. {
  51. return CreateValidateNumber(length);
  52. }
  53. temp = t;
  54. randomCode += CharArray[t];
  55. }
  56. return randomCode;
  57. }
  58. /// <summary>
  59. /// 创建验证码的图片
  60. /// </summary>
  61. /// <param name="context">context对象</param>
  62. /// <param name="validateNum">验证码</param>
  63. public void CreateValidateGraphic(HttpContext context,string validateNum)
  64. {
  65. int iwidth = (int)(validateNum.Length * 14);
  66. Bitmap image = new Bitmap(iwidth, 22);
  67. Graphics g = Graphics.FromImage(image);
  68. try
  69. {
  70. //生成随机生成器
  71. Random random = new Random();
  72. //清空图片背景色
  73. g.Clear(Color.White);
  74. //画图片的干扰线
  75. for (int i = 0; i < 25; i++)
  76. {
  77. int x1 = random.Next(image.Width);
  78. int x2 = random.Next(image.Width);
  79. int y1 = random.Next(image.Height);
  80. int y2 = random.Next(image.Height);
  81. g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
  82. }
  83. Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
  84. LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
  85. Color.Blue, Color.DarkRed, 1.2f, true);
  86. g.DrawString(validateNum, font, brush, 3, 2);
  87. //画图片的前景干扰点
  88. for (int i = 0; i < 100; i++)
  89. {
  90. int x = random.Next(image.Width);
  91. int y = random.Next(image.Height);
  92. image.SetPixel(x, y, Color.FromArgb(random.Next()));
  93. }
  94. //画图片的边框线
  95. g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
  96. //保存图片数据
  97. MemoryStream stream = new MemoryStream();
  98. image.Save(stream, ImageFormat.Jpeg);
  99. //输出图片
  100. context.Response.Clear();
  101. context.Response.ContentType = "image/jpeg";
  102. context.Response.BinaryWrite(stream.ToArray());
  103. }
  104. finally
  105. {
  106. g.Dispose();
  107. image.Dispose();
  108. }
  109. }
  110. /// <summary>
  111. /// 得到验证码图片的长度
  112. /// </summary>
  113. /// <param name="validateNumLength">验证码的长度</param>
  114. /// <returns></returns>
  115. public static int GetImageWidth(int validateNumLength)
  116. {
  117. return (int)(validateNumLength * 14);
  118. }
  119. /// <summary>
  120. /// 得到验证码图片的高度
  121. /// </summary>
  122. /// <returns></returns>
  123. public static double GetImageHeight()
  124. {
  125. return 22;
  126. }
  127. }
复制代码

附:完整实例代码点击此处本站下载

更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net操作json技巧总结》、《asp.net字符串操作技巧汇总》、《asp.net操作XML技巧总结》、《asp.net文件操作技巧汇总》、《asp.net ajax技巧总结专题》及《asp.net缓存操作技巧总结》。

希望本文所述对大家asp.net程序设计有所帮助。



回复

使用道具 举报