asp.net的验证码插件及方法、ashx验证码一般处理程序

需要引入一个ashx的一般处理程序!
把这个程序在前台当作一个图片使用就可以!

前台代码:

<td>
         <img title="看不清?" style=" cursor:pointer ;vertical-align:middle" width="45px" src="../ValidateCode.ashx"   onclick="this.src='../ValidateCode.ashx?_='+Math.random()" />
</td>


cursor:pointer  光标呈现为指示链接的指针(一只手)
onclick             点击切换图片
Math.random()随机数,改变切换地址,有些浏览器点击的时候不自动切换,直接调用缓存文件(如IE)

验证码一般处理程序ashx:
不知道为什么传不上来啊附件,我就把代码贴上来吧,大家回去用这个代码建立一个ashx的文件就OK了

建议验证码存到【session】里面,下面的代码是存到session里的(使用其他方法的可以注释掉context.Session["code"] = code;)

//一般处理程序中使用session,必须实现一个接口
首先添加一个命名空间“using System.Web.SessionState;”
我把我的后台登录的判断处代码贴到下面,也许对大家的理解有帮助。。。。

<%@ WebHandler Language="C#" Class="ValidateCode" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class ValidateCode : IHttpHandler, IRequiresSessionState {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        string code = GetRndStr();//生成4个随机的字符
        
        //记录生成的验证码到session
        context.Session["code"] = code;
  
        using (Bitmap img = CreateImages(code, "ch"))
        {
            img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 数字随机数
    /// </summary>
    /// <returns></returns>
    private string GetRndNum()
    {
        string code = string.Empty;
        Random random = new Random();
        for (int i = 0; i < 4; i++)
        {
            code += random.Next(9);
        }
        return code;
    }
    /// <summary>
    ///  英文随机
    /// </summary>
    /// <returns></returns>
    private string GetRndStr()
    {
        string Vchar = "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";
        string[] VcArray = Vchar.Split(',');
        string checkCode = string.Empty;
        Random rand = new Random();
        for (int i = 0; i < 4; i++)
        {
            int t = rand.Next(VcArray.Length);
            checkCode += VcArray[t];
        }
        return checkCode;
    }
    /// <summary>
    /// 中文随机
    /// </summary>
    /// <returns></returns>
    private string GetRndCh()
    {
        System.Text.Encoding gb = System.Text.Encoding.Default;//获取GB2312编码页(表)
        object[] bytes = CreateRegionCode(4);//生4个随机中文汉字编码
        string[] str = new string[4];
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < 4; i++)
        {
            //根据汉字编码的字节数组解码出中文汉字
            str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
            sb.Append(str[i].ToString());
        }
        return sb.ToString();
    }
    /// <summary>
    /// 产生随机中文字符
    /// </summary>
    /// <param name="strlength"></param>
    /// <returns></returns>
    private static object[] CreateRegionCode(int strlength)
    {
        //定义一个字符串数组储存汉字编码的组成元素
        string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
        Random rnd = new Random();
        object[] bytes = new object[strlength];

        for (int i = 0; i < strlength; i++)
        {
            //区位码第1位
            int r1 = rnd.Next(11, 14);
            string str_r1 = rBase[r1].Trim();
            //区位码第2位
            rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);
            int r2;
            if (r1 == 13)
            {
                r2 = rnd.Next(0, 7);
            }
            else
            {
                r2 = rnd.Next(0, 16);
            }
            string str_r2 = rBase[r2].Trim();

            //区位码第3位
            rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机种子
            int r3 = rnd.Next(10, 16);
            string str_r3 = rBase[r3].Trim();

            //区位码第4位
            rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
            int r4;
            if (r3 == 10)
            {
                r4 = rnd.Next(1, 16);
            }
            else if (r3 == 15)
            {
                r4 = rnd.Next(0, 15);
            }
            else
            {
                r4 = rnd.Next(0, 16);
            }
            string str_r4 = rBase[r4].Trim();
            //定义两个字节变量存储产生的随机汉字区位码
            byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
            byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);

            //将两个字节变量存储在字节数组中
            byte[] str_r = new byte[] { byte1, byte2 };

            //将产生的一个汉字的字节数组放入object数组中
            bytes.SetValue(str_r, i);
        }
        return bytes;
    }
    /// <summary>
    /// 画图片的背景图+干扰线 
    /// </summary>
    /// <param name="checkCode"></param>
    /// <returns></returns>
    private Bitmap CreateImages(string checkCode, string type)
    {
        int step = 0;
        if (type == "ch")
        {
            step = 5;//中文字符,边界值做大
        }
        int iwidth = (int)(checkCode.Length * (13 + step));
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 33);
        Graphics g = Graphics.FromImage(image);
        g.Clear(Color.White);//清除背景色
        Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };//定义随机颜色
        string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
        Random rand = new Random();

        for (int i = 0; i < 50; i++)
        {
            int x1 = rand.Next(image.Width);
            int x2 = rand.Next(image.Width);
            int y1 = rand.Next(image.Height);
            int y2 = rand.Next(image.Height);
            g.DrawLine(new Pen(Color.LightGray, 1), x1, y1, x2, y2);//根据坐标画线
        }

        for (int i = 0; i < checkCode.Length; i++)
        {
            int cindex = rand.Next(7);
            int findex = rand.Next(5);

            Font f = new System.Drawing.Font(font[findex], 15, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(c[cindex]);
            int ii = 4;
            if ((i + 1) % 2 == 0)
            {
                ii = 2;
            }
            g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * (12 + step)), ii);

        }
        g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        return image;
    }
}
View Code

判断session后天代码:

       protected void btnLogin_Click(object sender, EventArgs e)
        {

            //学生  1  老师 2
            string type = ddl.SelectedValue;
            string no = txtNo.Text.Trim();
            string pwd = txtPwd.Text.Trim();
            //md5加密
            pwd =   Common.GetMd5(pwd);


            string code = txtCode.Text.Trim();
             
            //验证码正确    因为session有过期失效的问题,
           //ps:session在服务器上默认保存20分钟
            if (Session["code"] != null &&  code.ToLower() == Session["code"].ToString().ToLower())
            {
                //
                Session.Remove("code");
                string msg;
                //学生
                if (type == "1")
                { //判断用户名密码是否正确
                    ItcastOCSS.BLL.Student bll = new ItcastOCSS.BLL.Student();
                    ItcastOCSS.Model.Student stu = new ItcastOCSS.Model.Student();
                    if (bll.Login(no, pwd, out msg, out stu))
                    {
                        //记录登陆成功的状态
                        Session["user"] = stu;
                        //跳转
                        Response.Redirect("Student/Index.aspx");
                    }
                    lblMsg.Text = msg;
                }
                else if (type == "2")
                { 
                    //老师
                    ItcastOCSS.BLL.Teacher bll = new ItcastOCSS.BLL.Teacher();
                    ItcastOCSS.Model.Teacher tea = new ItcastOCSS.Model.Teacher();
                    if (bll.Login(no, pwd, out msg, out tea))
                    {
                        Session["user"] = tea;
                        //跳转
                        if (tea.TIsAdmin == 1)
                        {
                            //管理员
                            Response.Redirect("Admin/Index.aspx");
                        }
                        else if(tea.TIsAdmin == 0)
                        { 
                            //老师
                            Response.Redirect("Teacher/Index.aspx");
                        }
                    }
                }
                
            }
            else
            { 
                //验证码错误
                lblMsg.Text = "验证码错误";
            }
            
        }
View Code


另外一个

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CZBK.ItcastProject.Common
{
    public class ValidateCode
    {
        public ValidateCode()
        {
        }
        /// <summary>
        /// 验证码的最大长度
        /// </summary>
        public int MaxLength
        {
            get { return 10; }
        }
        /// <summary>
        /// 验证码的最小长度
        /// </summary>
        public int MinLength
        {
            get { return 1; }
        }
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length">指定验证码的长度</param>
        /// <returns></returns>
        public string CreateValidateCode(int length)
        {
            int[] randMembers = new int[length];
            int[] validateNums = new int[length];
            string validateNumberStr = "";
            //生成起始序列值
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);
            int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
            int[] seeks = new int[length];
            for (int i = 0; i < length; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成随机数字
            for (int i = 0; i < length; i++)
            {
                Random rand = new Random(seeks[i]);
                int pownum = 1 * (int)Math.Pow(10, length);
                randMembers[i] = rand.Next(pownum, Int32.MaxValue);
            }
            //抽取随机数字
            for (int i = 0; i < length; i++)
            {
                string numStr = randMembers[i].ToString();
                int numLength = numStr.Length;
                Random rand = new Random();
                int numPosition = rand.Next(0, numLength - 1);
                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
            }
            //生成验证码
            for (int i = 0; i < length; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
        }

        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        /// <param name="containsPage">要输出到的page对象</param>
        /// <param name="validateNum">验证码</param>
        public void CreateValidateGraphic(string validateCode, HttpContext context)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 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, y1, x2, y2);
                }
                Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                //渐变.
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 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);
                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                context.Response.Clear();
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(stream.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        /// <summary>
        /// 得到验证码图片的长度
        /// </summary>
        /// <param name="validateNumLength">验证码的长度</param>
        /// <returns></returns>
        public static int GetImageWidth(int validateNumLength)
        {
            return (int)(validateNumLength * 12.0);
        }
        /// <summary>
        /// 得到验证码的高度
        /// </summary>
        /// <returns></returns>
        public static double GetImageHeight()
        {
            return 22.5;
        }
    }
}
View Code

本文转自:http://www.nbcoder.net/thread-337-1-1.html

原文地址:https://www.cnblogs.com/xiaoshi657/p/4113777.html