2025年4月15日 星期二 乙巳(蛇)年 正月十六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

ASP.NET生成图片验证码

时间:12-18来源:作者:点击数:33

今天开始做一个新项目,包含完整的注册登陆流程,在登陆时需要输入验证码防止暴力破解。

制作思路是这样的:

准备使用handler一般处理程序来写,先随机从0-9和A-Z里随机取4个数字,将内容保存在Session中供验证时使用。然后使用Bitmap和Graphics画图,最后以image/png类型输出流。

具体代码如下:

  • using System;
  • using System.Collections.Generic;
  • using System.Drawing;
  • using System.Linq;
  • using System.Web;
  • using System.Web.SessionState;
  • namespace MyCms.Handler
  • {
  • /// <summary>
  • /// VerificationCode 的摘要说明
  • /// </summary>
  • public class VerificationCode : IHttpHandler, IRequiresSessionState
  • {
  • public void ProcessRequest(HttpContext context)
  • {
  • System.Random rand = new Random();
  • int len = 4; //rand.Next(4, 6);
  • char[] chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
  • System.Text.StringBuilder myStr = new System.Text.StringBuilder();
  • for (int iCount = 0; iCount < len; iCount++)
  • {
  • myStr.Append(chars[rand.Next(chars.Length)]);
  • }
  • string verificationCode = myStr.ToString();
  • context.Session["VerificationCode"] = verificationCode;
  • Size ImageSize = Size.Empty;
  • using (Bitmap bmp = new Bitmap(121, 40)) {
  • using (Graphics g = Graphics.FromImage(bmp)) {
  • SolidBrush brush = new SolidBrush(Color.FromArgb(79, 137, 205));
  • g.Clear(Color.FromArgb(197,227,240));
  • g.DrawString(verificationCode, new Font("MS Sans Serif", 26,FontStyle.Strikeout,GraphicsUnit.Pixel), brush, new PointF(18, 6));
  • }
  • using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
  • bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  • context.Response.ContentType = "image/png";
  • ms.WriteTo(context.Response.OutputStream);
  • }
  • }
  • }
  • public bool IsReusable
  • {
  • get
  • {
  • return false;
  • }
  • }
  • }
  • }

当然在handler中想要使用session的话还需要实现IRequiresSessionState接口,否则是无法操作Session的。

源文件下载:

VerificationCode.rar

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门