软件编程
位置:首页>> 软件编程>> C#编程>> C#使用GDI+实现生成验证码

C#使用GDI+实现生成验证码

作者:springsnow  发布时间:2023-04-10 10:42:44 

标签:C#,GDI+,验证码

一、概述

一般处理程序 ashx :它没有服务器控件,用response输出什么就是什么。

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

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

C#使用GDI+实现生成验证码

二、一般处理程序

public class CheckCodeHandler : IHttpHandler, IRequiresSessionState//使用到Session,需要实现此接口IRequiresSessionState
   {
       private int intLength = 5;        //长度
       private string strIdentify = "Identify"; //随机字串存储键值,以便存储到Session中

/// <summary>
       /// 生成验证图片核心代码
       /// </summary>
       /// <param name="context"></param>
       public void ProcessRequest(HttpContext context)
       {
           //背景用白色填充
           Bitmap map = new Bitmap(200, 60);
           Graphics g = Graphics.FromImage(map);
           g.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);

//将随机生成的字符串绘制到图片上
           string letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
           Random r = new Random();
           StringBuilder s = new StringBuilder();
           Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);

for (int i = 0; i < intLength; i++)
           {
               s.Append(letters.Substring(r.Next(0, letters.Length - 1), 1));
               g.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(Color.Blue), i * 38, r.Next(0, 15));
           }
           font.Dispose();
           context.Session[strIdentify] = s.ToString(); //先保存在Session中,验证与用户输入是否一致

//生成干扰线条,混淆背景
           Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
           for (int i = 0; i < 10; i++)
           {
               g.DrawLine(pen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
           }
           pen.Dispose();

//设置输出流图片格式
           context.Response.ContentType = "image/gif";
           map.Save(context.Response.OutputStream, ImageFormat.Gif);
           map.Dispose();

context.Response.End();
       }
       public bool IsReusable
       {
           get
           {
               return false;
           }
       }
   }

三、在页面调用

<img src="CheckCodeHandler.ashx" alt="验证码" style="width: 60px; height: 24px" />
if (this.TextBox1.Text.ToUpper().Trim() != Session["strIdentify"].ToString().ToUpper().Trim())
{
   Response.Write("<script>alert('验证码不正确')</script>");
}
else
{
   Response.Write("<script>alert('登录成功')</script>");
}

来源:https://www.cnblogs.com/springsnow/p/9433975.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com