在ASP.NET下实现数字和字符相混合的验证码(C# Code)

原创:chi0591 日期:2003-12-30 人气:24

为了便于大家学习,修改vb.net code成为c#

gif.aspx文件修改的内容

private void Page_Load(object sender, System.EventArgs e)
{
    // 在此处放置用户代码以初始化页面
    // RndNum是一个自定义函数
    string VNum = RndNum(5);
    Session["VNum"] = VNum;
    ValidateCode(VNum);
}

private void ValidateCode(string VNum)
{
    //生成验证code
    System.Drawing.Bitmap img;
    System.Drawing.Graphics g;
    System.IO.MemoryStream ms;
    int gheight = Convert.ToInt32(VNum.Length * 11.5);
    //gheight为图片宽度,根据字符长度自动更改图片宽度
    img = new Bitmap(gheight, 20);
    g = Graphics.FromImage(img);
    //在矩形内绘制字串(字串,字体,画笔颜色,左上x.左上y)
    g.DrawString(VNum, new Font("Arial", 10), new SolidBrush(System.Drawing.Color.Blue), 3, 3);
    ms = new MemoryStream();
    img.Save(ms, ImageFormat.Png);

    Response.ClearContent(); //需要输出图象信息 要修改HTTP头
    Response.ContentType = "image/gif";
    Response.BinaryWrite(ms.ToArray());
    g.Dispose();
    img.Dispose();
    Response.End();
}

// '函数名称:RndNum
// '函数参数:VcodeNum--设定返回随机字符串的位数
// '函数功能:产生数字和字符混合的随机字符串
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,W,X,Y,Z";
    string[] VcArray = Vchar.Split(",".ToCharArray()); //将字符串生成数组
    string VNum = "";
    int i;
    for (i = 1; i < VcodeNum; i++)
    {
        System.Random ro = new Random();
        double decA = ro.NextDouble();
        VNum = VNum + VcArray[Convert.ToInt32(35 * decA)];
    }
    // For i=1 to VcodeNum
    // Randomize
    // VNum=VNum & VcArray(Int(35*Rnd)) '数组一般从0开始读取,所以这里为35*Rnd
    // Next
    return VNum;
}

ValidateCode.aspx修改内容

private void Page_Load(object sender, System.EventArgs e)
{
    // 在此处放置用户代码以初始化页面 
    string VNum;
    if (Session["VNum"] != null)
    {
        VNum = Session["VNum"].ToString();
        Session.Abandon();
        ViewState["VNum"] = VNum;
    }
}

private void Button1_Click(object sender, System.EventArgs e)
{
    if (txtValidateCode.Text == ViewState["VNum"].ToString())
    {
        lblShow.Text = "提示:验证通过";
    }
    else
    {
        lblShow.Text = "所填写的验证码与所给的不符";
    }
}

来源:不详

Contributors: FHL