ITPub博客

首页 > Linux操作系统 > Linux操作系统 > asp.net实现验证码功能(源码)

asp.net实现验证码功能(源码)

原创 Linux操作系统 作者:iDotNetSpace 时间:2009-02-23 16:17:13 0 删除 编辑

听说很多新手都为 验证码 烦恼,小弟特写此一文,希望对大家有帮助

新建image.aspx页面

image.aspx.cs代码如下:
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;


public partial class image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string tmp = RndNum(4);
        HttpCookie a = new HttpCookie("ImageV",tmp);
        Response.Cookies.Add(a);
        this.ValidateCode(tmp);
    }

    private void ValidateCode(string VNum)
{
        Bitmap Img=null;
        Graphics g=null;
        MemoryStream ms=null;

        int gheight=VNum.Length*12;
        Img=new Bitmap(gheight,25);
        g=Graphics.FromImage(Img); 
        //背景颜色 
        g.Clear(Color.White); 
        //文字字体 
        Font f=new Font("Arial Black",10); 
        //文字颜色 
        SolidBrush s=new SolidBrush(Color.Black);
        g.DrawString(VNum,f,s,3,3);
        ms=new MemoryStream();
        Img.Save(ms,ImageFormat.Jpeg);
        Response.ClearContent();
        Response.ContentType="image/Jpeg";
        Response.BinaryWrite(ms.ToArray());

        g.Dispose();
        Img.Dispose();
        Response.End();
}

        private string RndNum(int VcodeNum)
        {
            string Vchar="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";
            string[] VcArray=Vchar.Split(new Char [] {','});
            string VNum="";        
            int temp=-1;

            Random rand=new Random();

            for(int i=1;i            {
                if(temp!=-1)
            {
            rand=new Random(i*temp*unchecked((int)DateTime.Now.Ticks));
         }

            int t=rand.Next(35);
            if(temp!=-1&&temp==t)
            {
                return RndNum(VcodeNum);
            }
            temp=t;
            VNum+=VcArray[t];
       }
            Session["image"] = VNum;
            return VNum;
        }
}

新建测试页面(default.aspx)

添加image控件

 

添加TextBox

添加Button

后台Button1_Click事件代码:

            String img = this.TextBox1.Text.trim();
        if (Session["image"] != null)
        {
            if (img.Equals(Session["image"].ToString()))
            {
                 Response.Write("");                                
            }
            else
            {
                 Response.Write("");                               
            }

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-557459/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5321635