ASP.NET验证码实现(附源码)

所属分类: 网络编程 / ASP.NET 阅读数: 436
收藏 0 赞 0 分享

首先看下效果实现(由于gif屏幕录制软件是即时找的,有些失祯)

代码主要就是绘制验证码类的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;

namespace SecurityCodePic
{
 public class DrawingSecurityCode
 {
  /// <summary>
  /// 生成验证码,并返回
  /// </summary>
  /// <returns></returns>
  public string GetSecurityCode(int n)
  {
   string code = GenerateCheckCode(n);
   CreateCheckCodeImage(code);
   return code;
  }

  /// <summary>
  /// 动态生成指定数目的随机数或字母
  /// </summary>
  /// <param name="num">整数</param>
  /// <returns>返回验证码字符串</returns>
  private string GenerateCheckCode(int num)
  {
   int number;//定义变量
   char code;
   string checkCode = String.Empty; //空字符串,只读
   Random random = new Random(); //定义随机变量实例
   for (int i=0; i < num;i++ )
   {
    //利用for循环生成指定数目的随机数或字母
    number = random.Next(); //返回一个小于指定的最大值的非负的随机数 next有三个构造函数 
    if (number % 2 == 0)
    {//产生一个一位数
     code = (char)('0' + (char)(number % 10));
    }
    else
    { //产生一个大写字母
     code = (char)('A'+(char)(number % 26));
    }
    checkCode += code.ToString();
   }
   return checkCode;
  }

  /// <summary>
  /// 根据验证码字符串生成验证码图片
  /// </summary>
  /// <param name="checkCode">验证码字符串</param>
  private void CreateCheckCodeImage(string checkCode)
  {

   if (checkCode == null || checkCode.Trim() == String.Empty) return;
   // 引用System.Drawing类库
   Bitmap myImage = new Bitmap(80, 30);//生成一个指定大小的位图
   Graphics graphics = Graphics.FromImage(myImage); //从一个位图生成一个画布
   try
   {
    graphics.Clear(Color.White); //清除整个绘画面并以指定的背景色填充,这里是把背景色设为白色
    Random random = new Random(); //实例化一个伪随机数生成器

    //画图片的前景噪音点,这里有100个
    for (int i = 0; i < 100; i++)
    {
     int x = random.Next(myImage.Width);
     int y = random.Next(myImage.Height);
     myImage.SetPixel(x, y, Color.FromArgb(random.Next()));//指定坐标为x,y处的像素的颜色
    }

    //画图片的背景噪音线,这里为2条
    for (int i = 0; i < 2; i++)
    {
     int x1 = random.Next(myImage.Width);
     int x2 = random.Next(myImage.Width);
     int y1 = random.Next(myImage.Height);
     int y2 = random.Next(myImage.Height);
     graphics.DrawLine(new Pen(Color.Black), x1, y1, x2, y2); //绘制一条坐标x1,y1到坐标x2,y2的指定颜色的线条,这里的线条为黑色
    }

    Font font = new Font("Arial", 15, FontStyle.Bold); //定义特定的文本格式,这里的字体为Arial,大小为15,字体加粗
    //根据矩形、起始颜色和结束颜色以及方向角度产生一个LinearGradientBrush实例---线性渐变
    System.Drawing.Drawing2D.LinearGradientBrush brush =
     new System.Drawing.Drawing2D.LinearGradientBrush(
      new Rectangle(0, 0, myImage.Width, myImage.Height),//在坐标0,0处实例化一个和myImage同样大小的矩形
      Color.Blue, Color.Red, 1.2f, true);
    //绘制文本字符串
    graphics.DrawString(checkCode, font, brush, 2, 2);

    //绘制有坐标对、宽度和高度指定的矩形---画图片的边框线
    graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, myImage.Width - 1, myImage.Height - 1);
    //创建其支持存储器为内存的流
    MemoryStream ms = new MemoryStream();
    //将此图像以指定格式保存到指定的流中
    myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //这里是以gif的格式保存到内存中
    HttpContext.Current.Response.ClearContent(); //清除缓冲区流中的所有内容输出
    HttpContext.Current.Response.ContentType = "image/Gif"; //获取或设置输出流的HTTP MIME类型
    HttpContext.Current.Response.BinaryWrite(ms.ToArray()); //将一个二进制字符串写入HTTP输出流
   }
   finally
   {
    //释放占用资源
    graphics.Dispose();
    myImage.Dispose();
   }
  }
 }
}


然后使用SecurityCode.ashx文件调用上面类的方法实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SecurityCodePic
{
 /// <summary>
 /// SecurityCode1 的摘要说明
 /// </summary>
 public class SecurityCode1 : IHttpHandler
 {

  public void ProcessRequest(HttpContext context)
  {
   DrawingSecurityCode sc = new DrawingSecurityCode();
   string SecurityCode = sc.GetSecurityCode(6);
  }

  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
 }
}


最后就是ASP.NET页面图片路径的引用了

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SecurityCode_Test.aspx.cs" Inherits="SecurityCodePic.SecurityCode_Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>验证码的实现</title>
 <style type="text/css">
 #VCodeImg { cursor: pointer;}
 </style>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <img id="VCodeImg" src="SecurityCode.ashx" alt="验证码" onclick="javascript:RefreshCode();" />
 </div>
 </form>
 <script type="text/javascript">
  function RefreshCode() {
   var random = Math.random();
   var img = document.getElementById("VCodeImg");
   img.src = "SecurityCode.ashx?" + random; //加上无意义的随机参数,浏览器才会认为是新地址,就会重新读取数据
  }
 </script>
</body>
</html>

以上就是本文的全部,对了,还有源码下载分享给大家,欢迎大家下载。

源码分享:ASP.NET验证码实现

更多精彩内容其他人还在看

ASP.Net 之Datalist删除功能详解附代码

ASP.Net 之Datalist删除功能详解附代码,需要的朋友可以参考一下
收藏 0 赞 0 分享

ASP.NET(C#)验证数字的两种方法

ASP.NET(C#)验证数字的两种方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

此页的状态信息无效,可能已损坏 的处理办法及原因分析

此页的状态信息无效,可能已损坏 的处理办法及原因分析,需要的朋友可以参考一下
收藏 0 赞 0 分享

MultiLine 换行后实现读取不换行的具体思路

输入内容中有换行,保存到数据库,直接查看感觉没有换行,但查询结果“以文本格式显示结果”你就会发现 其实是有换行的,下面与大家分享下具体的解决方法
收藏 0 赞 0 分享

swfupload ajax无刷新上传图片实例代码

在这里上传图片就需要用到ajax无刷新上传图片,这里面包含的东西不是一点半点。这里用到的是一个插件swfupload实现无刷新上传图片,感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

静态gb2312编码在项目传值出现中文乱码现象

参考的美工静态页面是gb2312格式的,当此编码拿到项目中后,utf-8编码的系统,加载页面时,会出现样式问题,比如不能正常居中等
收藏 0 赞 0 分享

System.Timers.Timer定时执行程序示例代码

如果是某个逻辑功能的定时,可以将code放到逻辑功能的类的静态构造函数中,在该逻辑类第一次执行时,静态构造函数会被调用,则定时自然启动
收藏 0 赞 0 分享

分享下Asp.Net面试题目及答案集合

这篇文章主要是总结asp.net开发人员在面试过程中常遇到的一些问题小结,需要的朋友可以参考下
收藏 0 赞 0 分享

给自定义Web控件添加事件(前后台代码)

给自定义控件(Web Control)添加事件具体前后台代码如下,感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

ASP.NET过滤器的应用方法介绍

ASP.NET过滤器的应用方法介绍,需要的朋友可以参考一下
收藏 0 赞 0 分享
查看更多