asp.net 验证码

在项目中添加 ----- 新建项  ------   一般处理程序;

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


namespace WebApplication1
{
    /// <summary>
    /// Yanzhengma 的摘要说明
    /// </summary>
    public class Yanzhengma : IHttpHandler, IRequiresSessionState
    {


        public void ProcessRequest(HttpContext context)
        {
            var Response = context.Response;
            Response.ContentType = "image/jpeg"; //需要输出图象信息 要修改HTTP头 


            int size = 5;//验证码的长度


            string authCode = GetRandomNumberString(size);// 获得验证码字符


            //在生成验证码的地方将验证码放到Session中,这样在用的时候就能从Session中取出正确的验证码了
            context.Session["AuthCode"] = authCode;
            using (Bitmap theBitmap = CreateImage(authCode))// 获得验证码图片
            {
                theBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            Response.End();
        }
        private string GetRandomNumberString(int codeCount)
        {
            string strChoice = "2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] strResult = strChoice.Split(new Char[] { ',' });
            string strReturn = "";
            Random rnd = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                int j = rnd.Next(strResult.Length);//随机数不能大于数组的长度
                strReturn = strReturn + strResult[j].ToString();
            }
            return strReturn;
        }


        private Bitmap CreateImage(string str_AuthCode)
        {
            int width = str_AuthCode.Length * 13;
            int height = 20;
            Random rad = new Random();
            Bitmap bmp = new Bitmap(width, height);
            using (Graphics grp = Graphics.FromImage(bmp))
            {
                grp.Clear(Color.White);//填充bmp的背景色
                grp.DrawRectangle(new Pen(Color.Red, 1), 0, 0, width - 1, height - 1);//绘制边框
                int num = width * height;
                for (int i = 0; i < num; i += 3)//在图片的指定坐标上画上有颜色的圆点
                {
                    int x = rad.Next(width);
                    int y = rad.Next(height);
                    int r = rad.Next(255);
                    int g = rad.Next(255);
                    int b = rad.Next(255);
                    Color c = Color.FromArgb(r, g, b);
                    bmp.SetPixel(x, y, c);//在图片的指定坐标上画上有颜色的圆点
                }


                using (Font f = new Font("宋体", 12, FontStyle.Bold))//定义字体
                {
                    using (Brush br = new SolidBrush(Color.Black))//定义画笔的颜色及字体的颜色
                    {
                        for (int i = 0; i < str_AuthCode.Length; i++)
                        {
                            string s = str_AuthCode.Substring(i, 1);//单个单个的将字画到图片上
                            Point p = new Point(i * 12 + rad.Next(3), rad.Next(3) + 1);//字体出现的位置(坐标)
                            grp.DrawString(s, f, br, p);//绘制字符串
                        }
                    }
                }
                return bmp;//返回
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


然后再需要使用验证码的页面

1、加上一个Textbox控件,用来让用户输入验证码

2、<img src=“这里填刚才添加的一般处理程序的名字.ashx” id=“img1”οnclick="shuaxin();" />

3、 <a href="#" οnclick="shuaxin();">看不清,刷新一下</a>//用来点击刷新验证码

4、 <asp:Button ID="Button1" runat="server" Text="登录" οnclick="Button1_Click" />//这个按钮这里用来验证  验证码 输入的是否正确,实际使用中不一定是这个。

5、   在此页面的JS中写

        function shuaxin() 

         {   
            document.getElementById('img1').setAttribute('src', 'Yanzhengma.ashx?id='+Math.random());
        }

6、  添加上面那个按钮的事件,验证 用户输入的验证码是否正确      

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Session["AuthCode"].ToString() == TextBox1.Text.ToUpper())   //ToUpper()将字符串转换为大写
            {
                Response.Write("输入正确");
            }
            else
            {
                Response.Write("输入错误");
            }
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值