ASP.NET生成随机验证码代码和看不清切换验证码的小结

长平狐 发布于 2013/01/06 11:24
阅读 2K+
收藏 0

经过亲自测试,本代码复制并按照说明,可以直接运行

 

============================================================

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

public partial class CheckCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.CreateCheckCodeImage(GenerateCheckCode());
    }

    /// <summary>
    /// 创建随机生成的验证码,可以为数字或字母
    /// </summary>
    /// <returns></returns>

    private string GenerateCheckCode()
    {
        int number = 0;
        char code;
        string checkcode = string.Empty;

        // 随机生成数字,并转换成5个数字或字母
        System.Random random = new Random();
        for (int i = 0; i < 5; i++)
        {
            number = random.Next();
            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10)); // 数字
            else
                code = (char)('A' + (char)(number % 26)); // 字母

            checkcode += code.ToString();
        }
        Response.Cookies.Add(new HttpCookie("CheckCode", checkcode));
        return checkcode;
    }

    /// <summary>
    /// 创建随机验证的图片,包括背景色和前景色
    /// </summary>
    /// <param name="checkcode"></param>
    private void CreateCheckCodeImage(string checkcode)
    {
        if (checkcode == null || checkcode.Trim() == string.Empty)
            return;

        Bitmap image = new Bitmap((int)Math.Ceiling((checkcode.Length * 12.8)), 24);
        Graphics grp = Graphics.FromImage(image);

        try
        {
            // 产生随机生成码
            Random random = new Random();

            // 清空图片背景色
            grp.Clear(Color.White);

            // 画图片的背景噪音线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                grp.DrawLine(new Pen(Color.SpringGreen), x1, x2, y1, y2);
            }
            Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            grp.DrawString(checkcode, font, brush, 2, 2);

            // 画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            // 画图片的边框线
            grp.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        catch (System.Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            // 清除类对象(Graphics和Bitmap)
            grp.Dispose();
            image.Dispose();
            grp = null;
            image = null;
        }
    }
}

 

生成随机验证码的配置说明:

假如以上验证码生成器页面名为:CheckCode.aspx,那么在登录页面中使用“<IMG>” 这个 HTML 元素来显示生成的验证码图片:<IMG src="CheckCode.aspx">
在登录页面的登录按钮的处理事件中使用以下代码判断验证码:

  private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
  {
   if(Request.Cookies["CheckCode"] == null)
   {
    lblMessage.Text = "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";
    lblMessage.Visible = true;
    return;
   }

   if(String.Compare(Request.Cookies["CheckCode"].Value, txtCheckCode.Text, true) != 0)
   {
    lblMessage.Text = "验证码错误,请输入正确的验证码。";
    lblMessage.Visible = true;
    return;
   }

 

添加图片,便切换验证码设置:

<img src="CheckCode.aspx" alt="若看不清,点击更换一张!!" onclick="this.src=this.src+'?'" />

 

转载声明: 本文转自http://wyzhjmy.blog.163.com/blog/static/7234753520093353751852/

=====================================================================

 

另外,亦可参考:

无刷新更换验证码

现在越来越多的网站的注册、发布等页面都采用了防止一些恶意程序的图片验证码选项,不知道大家有没有碰到这样的情况,一个注册表单,填写了帐号信息、个人信息,最后一项的验证码太模糊了竟然看不清,只能是重新刷新整个页面来刷新图片验证码的内容,这是一个不良好的交互设计。参考了一些门户网站的方法,我的改进设计思路如下:

把验证码输入项放在表单的第一行;客户端可以在不刷新整个页面的情况下更新图片验证码的内容。

我们一般要插入验证码都是使用<img />标签,例如<img src="validate.aspx" />,其中validate.aspx是一个生成图片的程序文件。为了能够更新验证码的内容,可以在图片旁边加一个更新的链接,单击触发图片重载事件,完成图片验证码的更换。具体代码如下:

<a href="javascript:reloadcode();" title="更换一张验证码图片"><img src="validate.aspx" id="safecode" alt="看不清,请换一张" /></a> <a href="javascript:reloadcode();" title="更换一张验证码图片">看不清,请换一张</a>

 

<script language="JavaScript">
function reloadcode()
{
     document.getElementById('safecode').src = 'validate.aspx?' + Math.random();
}
</script>


注意:在reloadcode函数中,我们在code.asp后面加了一个随机参数,这样每次的链接地址都不一样,从而达到更新的目的。

<img src="validate.aspx"id="safecode" border="0" style="cursor:pointer;" onClick="this.src='validate.aspx?t='+Math.random()" alt="点击更换验证码">

===============================================================================

 

无刷新更换验证码

<script language ="javascript" type ="text/javascript">
function reloadcode()
{
document.getElementById('safecode').src = 'test.aspx?' + Math.random();
}
script>
<a href="javascript:reloadcode();" title="更换一张验证码图片">
<IMG src="test.aspx" id="safecode" alt="看不清,点击换张验证码">a>
在reloadcode函数中,我们在code.asp后面加了一个随机参数,这样每次的链接地址都不一样,从而达到更新的目的。

---------------------------------------------------------------------------------------

    <img src="manage_product_checkCode.aspx" id="safecode" alt="看不清,点击换张验证码"/>
    <a href="javascript:reloadcode()" title="更换一张验证码图片">更换一张验证码图片
    </a> 

---------------------------------------------------------------------------------------

转载声明: 本文转自http://czm600604604.blog.163.com/blog/static/8252068200981091443438/

无刷新更换验证码

页面中代码

<script language="javascript">
      function change()
      {
          var img =document.getElementById("Image1");
          img.src=img.src+'?';
      }
</script>

<img id="Image1" src="Image.aspx"/><a href="javascript:change();">看不清,换一张</a>

=====================================================================

图形验证码+“看不清楚换一张”

Image.aspx.cs 中代码

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Design;


//生成随机字符串
public partial class Image : System.Web.UI.Page
{
    private string CreateRandomNum(int NumCount)
    {
        string allChar = "0,1,2,3,4,5,6,7,8,9";
        string[] allCharArray = allChar.Split(',');
        string randomNum = "";
        int temp = +1;
        Random rand = new Random();
        for (int i = 0; i < NumCount; i++)
        {
            if (temp != -1)
            {
                rand = new Random(temp * ((int)DateTime.Now.Ticks));
            }
            int t = rand.Next(10);
            if (temp == t)
            {
                return CreateRandomNum(NumCount);
            }
            temp = t;
            randomNum += allCharArray[t];
        }
        return randomNum;
    }
    //生成图片
    private void CreateImage(string validateNum)
    {
        if (validateNum == null || validateNum.Trim() == String.Empty)
            return;
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(validateNum.Length * 12 + 10, 22);
        Graphics g = Graphics.FromImage(image);
        try
        {
            Random random = new Random();
            g.Clear(Color.White);
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Silver), x1, x2, y1, y2);
            }
            Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(validateNum, font, brush, 2, 2);
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string validateNum = CreateRandomNum(4);
            CreateImage(validateNum);
            Session["ValidateNum"] = validateNum;
        }
        }
}


页面中代码

<script language="javascript">
      function change()
      {
          var img =document.getElementById("Image1");
          img.src=img.src+'?';
      }
</script>

<img id="Image1" src="Image.aspx"/><a href="javascript:change();">看不清,换一张</a>

 

转载声明: 本文转自http://zzpdownload.blog.163.com/blog/static/83231134200912643320729/

 

=====================================================================

Javascript 验证码(尚未验证)

 

需要用到验证码,突然想能否用js做验证码呢?
当然js不能作图,但是可以用js模拟做验证码的
于是花了20分钟按照我的想法尝试做,最后做出来比我想象中的效果还要好,呵呵
先贴个图看看代码:

 

<!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>
    <title>无标题页</title>
    <style type="text/css">

        .code
        {
            background-image:url(code.jpg);
            font-family:Arial;
            font-style:italic;
            color:Red;
            border:0;
            padding:2px 3px;
            letter-spacing:3px;
            font-weight:bolder;
        }
        .unchanged
        {
            border:0;
        }
    
</style>
    <script language="javascript" type="text/javascript">
var code ; //在全局 定义验证码
     function createCode()
     { 
       code = "";
       var codeLength = 6;//验证码的长度
       var checkCode = document.getElementById("checkCode");
       var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');//所有候选组成验证码的字符,当然也可以用中文的
        
       for(var i=0;i<codeLength;i++)
       {
      
        
       var charIndex = Math.floor(Math.random()*36);
       code +=selectChar[charIndex];
       
       
       }
//       alert(code);
       if(checkCode)
       {
         checkCode.className="code";
         checkCode.value = code;
       }
       
     }
     
      function validate ()
     {
       var inputCode = document.getElementById("input1").value;
       if(inputCode.length <=0)
       {
           alert("请输入验证码!");
       }
       else if(inputCode != code )
       {
          alert("验证码输入错误!");
          createCode();//刷新验证码
       }
       else
       {
         alert("^-^ OK");
       }
       
       }
</script>
</head>
<body>
<form  action="#">
     <input  type="text"  onclick="createCode()" id="input1" />
    
    <input type="text"  id="checkCode" class="unchanged" style="width: 80px"  /><br />
    <input id="Button1"  onclick="validate();" type="button" value="确定" /> 
</form>
</body>
</html>

转载声明: 本文转自http://www.chenjiliang.com/Article/View.aspx?ArticleID=5449

=====================================================================


原文链接:http://blog.csdn.net/sunboy_2050/article/details/4974548
加载中
返回顶部
顶部