使用Asp.Net进行验证码生成就是使用图片生成实体进行操作,生成一张图片,并把图片上的内容存在Session中,下面是网络中查找的代码:
网站上验证码效果一般制作方法是:
1)使用HttpHandler(一般处理程序)绘制随机验证码的图,以及产生随机码,并输出到页面的OutputStream中。
2)页面中使用异步方式(js等)进行刷新当前页面的验证码。
【示例】
1)创建一个"一般应用处理程序ashx”,代码如下:
public class ValidationCode : IHttpHandler
{
//随机发生器
static Random r = new Random(Guid.NewGuid().GetHashCode());
//排除黑色、透明色颜色,因为底色黑色
static PropertyInfo[] colors = (typeof(Brushes).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Static)).Where(p => p.Name != "Black" && p.Name != "Transparent").Select(p => p).ToArray();
//排除黑色颜色,因为底色黑色
static PropertyInfo[] linecolors = (typeof(Pens).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Static)).Where(p => p.Name != "Black").Select(p => p).ToArray();
//获取静态类Brushes实例对象
static object colorobj = typeof(Brushes).GetConstructor(BindingFlags.NonPublic, null, Type.EmptyTypes, null);
//获取静态类Pens实例对象
static object penobj = typeof(Pens).GetConstructor(BindingFlags.NonPublic, null, Type.EmptyTypes, null);
//每个随机字符的宽度
const float PERNUMBERWIDTH = 40.0f;
//每个字符的高度
const float PERNUMBERHEIGHT = 50.0f;
public void ProcessRequest(HttpContext context)
{
//获取要产生多少随机数(默认产生5个)
int reqNum = 5;
if (context.Request.QueryString["reqNum"] != null)
{
int.TryParse(context.Request.QueryString["reqNum"], out reqNum);
}
//产生多少大的背景图
Bitmap bt = new Bitmap((int)(PERNUMBERWIDTH*reqNum), (int)PERNUMBERHEIGHT);
Graphics g = Graphics.FromImage(bt);
//产生4个随机数(number可以被保存到Session中)
string numbers = "";
//绘制数字
for (int i = 1; i <= reqNum; i++)
{
numbers += r.Next(0, 9).ToString();
var color = (PropertyInfo)colors.GetValue(r.Next(0, colors.Length));
context.Response.Write(color.Name + "<br/>");
Brush randomcolor = (Brush)color.GetValue(colorobj, null);
g.DrawString(numbers[i-1].ToString(), new Font("黑体", PERNUMBERWIDTH),randomcolor, new PointF((i-1)*PERNUMBERWIDTH, 0f));
}
//绘制随机线条
int linenum = r.Next(10, 21);
for (int i = 1; i <= linenum; i++)
{
var linecolor = (PropertyInfo)linecolors.GetValue(r.Next(0, colors.Length));
Pen randomcolor = (Pen)linecolor.GetValue(penobj, null);
g.DrawLine(randomcolor, new PointF((float)(r.NextDouble() * PERNUMBERWIDTH * reqNum), (float)(r.NextDouble() * PERNUMBERHEIGHT)), new PointF((float)(r.NextDouble() * PERNUMBERWIDTH * reqNum), (float)(r.NextDouble() * PERNUMBERHEIGHT)));
}
g.Dispose();
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
bt.Save(context.Response.OutputStream, ImageFormat.Jpeg);
bt.Dispose();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
评论列表: