ASP.NET在实际开发中验证码的用法

时间:2023-06-03 21:46:33
ASP.NET在实际开发中验证码的用法

在网上有看到很多关于验证码的代码,很多都只是生成一张验证码图片,然而在实际登陆验证模块,验证码要怎么添加进去或者说怎么运用、和实际项目开发中要怎么使用验证码,我自己总结了几点。

一、在实际开发登陆模块的验证码,程序员是将验证码的文本值(字符串)存在Session中的,然后在登陆验证的时候,通过Session取值进行判断的,这样效率会高很多。

二、然而在写验证码的时候要想通过Session存值,就必须实现System.Web.SessionState.IRequiresSessionState这个接口

三、以一般处理程序(ashx页面)为列,下面对验证码写法和运用进行详解

代码:

 using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web; namespace vcodeDemo
{
/// <summary>
/// vcode 写法的说明
/// </summary>
public class c01vcode : IHttpHandler,System.Web.SessionState.IRequiresSessionState
//如果要在一般处理程序中能够正常使用session则必须实现IRequiresSessionState接口
{
public void ProcessRequest(HttpContext context)
{
//1 设置ContentType为图片类型
context.Response.ContentType = "image/jpeg"; //2 准备要作画的图片对象,宽度为80 高度为25 ,Bitmap:位图
using (Image img = new Bitmap(, ))
{
// 从img对象上定义画家
using (Graphics g = Graphics.FromImage(img))
{
//以白色来清除位图的背景
g.Clear(Color.White); //画图片的边框为红色,从左上角开始画满整个图片
g.DrawRectangle(Pens.Red, , , img.Width - , img.Height - ); //在验证码文字前面画50个噪点
this.DrawPoint(, g, img.Width, img.Height); //得到验证码文本字符串(随机产生4个字符)
string vcode = this.GetVCode(); //保存验证码文本字符串到session中
context.Session["vcode"] = vcode; //将验证码字符串写入到图片对象上
g.DrawString(vcode
, new Font("Arial", , FontStyle.Strikeout | FontStyle.Bold) // 给文本加中横线和加粗
, new SolidBrush(Color.Red)
, new PointF(r.Next(), r.Next())
); //在验证码文字后面画50个噪点
this.DrawPoint(, g, img.Width, img.Height);
}
//将验证码输出给浏览器
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
} /// <summary>
/// 在图片对象上画噪点
/// </summary>
/// <param name="count"></param>
void DrawPoint(int count, Graphics g, int width, int height)
{
for (int i = ; i < count; i++)
{
int x = r.Next(width);
int y = r.Next(height); g.DrawLine(Pens.Blue
, new Point(x, y)
, new Point(x + , y + )
);
}
} /// <summary>
/// 定义产生随机数的对象
/// </summary>
Random r = new Random(); /// <summary>
/// 产生验证码文本字符串
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
string GetVCode(int count)
{
//声明返回值
string rescode = "";
string codestr = "ABCDabcd123456789";
char[] codeArr = codestr.ToArray();
for (int i = ; i < count; i++)
{
rescode += codeArr[r.Next(codestr.Length)];
}
//返回字符串
return rescode;
} public bool IsReusable
{
get
{
return false;
}
}
}
}

四、在验证登陆判断的时候,因为我们通过上下文对象的Session给验证码文本赋值并存入Session中去: context.Session["vcode"] = vcode;所有在进行验证的时候可以使用Session["vcode"]进行取值,然后进行判断。