设置登录时的图形验证码

首先建一个一般处理程序,命名为RandomCode.ashx

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Collections;
  6 using System.Configuration;
  7 using System.Data;
  8 using System.Web;
  9 using System.Web.UI;
 10 using System.Web.UI.WebControls;
 11 using System.Web.UI.WebControls.WebParts;
 12 using System.Web.UI.HtmlControls;
 13 using System.Drawing;
 14 
 15 namespace IntegritySystem.Web.Tools
 16 {
 17     /// <summary>
 18     /// RandomCode 的摘要说明
 19     /// </summary>
 20     public class RandomCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
 21     {
 22         public void ProcessRequest(HttpContext context)
 23         {
 24             string checkCode = GetRandomCode(5);
 25             context.Session["CheckCode"] = checkCode;
 26             SetPageNoCache();
 27             CreateImage(checkCode);
 28         }
 29         //获取验证码各个字母
 30         private string GetRandomCode(int CodeCount)
 31         {
 32             string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
 33             string[] allCharArray = allChar.Split(',');
 34             string RandomCode = "";
 35             int temp = -1;
 36             Random rand = new Random();
 37             for (int i = 0; i < CodeCount; i++)
 38             {
 39                 if (temp != -1)
 40                 {
 41                     rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
 42                 }
 43                 int t = rand.Next(33);
 44                 while (temp == t)
 45                 {
 46                     t = rand.Next(33);
 47                 }
 48                 temp = t;
 49                 RandomCode += allCharArray[t];
 50             }
 51             return RandomCode;
 52         }
 53 
 54         //页面设置没有缓存
 55         private void SetPageNoCache()
 56         {
 57            HttpContext.Current.Response.Buffer = true;
 58            HttpContext.Current.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
 59            HttpContext.Current.Response.Expires = 0;
 60            HttpContext.Current.Response.CacheControl = "no-cache";
 61            HttpContext.Current.Response.AppendHeader("Pragma", "No-Cache");
 62         }
 63 
 64         //设置背景图片
 65         private void CreateImage(string checkCode)
 66         {
 67             int iwidth = (int)(checkCode.Length * 14);
 68             System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 30);
 69             Graphics g = Graphics.FromImage(image);
 70             Font f = new System.Drawing.Font("Arial", 15);
 71             Brush b = new System.Drawing.SolidBrush(Color.Black);
 72             Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));
 73             g.Clear(System.Drawing.ColorTranslator.FromHtml("#fff"));//背景色
 74             char[] ch = checkCode.ToCharArray();
 75             for (int i = 0; i < ch.Length; i++)
 76             {
 77                 if (ch[i] >= '0' && ch[i] <= '9')
 78                 {
 79                     g.DrawString(ch[i].ToString(), f, r, 8 + (i * 12), 3);
 80                 }
 81                 else
 82                 {
 83                     g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
 84                 }
 85             }
 86             System.IO.MemoryStream ms = new System.IO.MemoryStream();
 87             image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
 88             HttpContext.Current.Response.Cache.SetNoStore();
 89             HttpContext.Current.Response.ClearContent();
 90             HttpContext.Current.Response.ContentType = "image/Jpeg";
 91             HttpContext.Current.Response.BinaryWrite(ms.ToArray());
 92             g.Dispose();
 93             image.Dispose();
 94         }
 95         public bool IsReusable
 96         {
 97             get
 98             {
 99                 return false;
100             }
101         }
102     }
103 }

然后前台调用:

           <input type="text" class="yzm" id="Codes" name="Codes" maxlength="6" style="width: 80px;
                        float: left;" />
                    <img id="codeimg" alt="验证码" src="/Tools/RandomCode.ashx" title="点击" style=" margin-bottom:-5px; cursor:pointer;"
                         onclick="EditCode(this)"/>

脚本点击事件:

 function EditCode() {
        document.getElementById("codeimg").src="/Tools/RandomCode.ashx?id="+Math.random();
    }

在就是后台验证就可以了:

 1           if (Session["CheckCode"] != null)
 2                 {
 3                     if (Codes.ToLower() != Session["CheckCode"].ToString().ToLower())
 4                     {
 5                         Message = "验证码输入错误,请输入正确的验证码!";
 6                         return Json(new { Success = b, ErrorMessage = Message }, JsonRequestBehavior.AllowGet);
 7                     }
 8                 }
 9                 else
10                 {
11                     Message = "验证码输入错误,请输入正确的验证码!";
12                     return Json(new { Success = b, ErrorMessage = Message }, JsonRequestBehavior.AllowGet);
13                 }

效果就是这样了,验证码个数可以调整:

 

posted @ 2016-10-12 10:16  渴死的鱼丶  阅读(800)  评论(0编辑  收藏  举报