生成随机码

来源:互联网 发布:淘宝网购物皮衣 编辑:程序博客网 时间:2024/05/17 00:51
 

首先建立一个getnum.aspx的网页,再复制下面代码
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public partial class getnum : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string checkCodeString = "0123456789abcdefghijklmnprqstuvwxyzABCDEFGHIJKLMNQPRTSVUWXYZ";//验证码中可能会出现的字符集合
        int length = checkCodeString.Length; //验证码字符集合的长度
        Font font = new Font("宋体", 15, FontStyle.Bold); //设置以宋体来绘制验证字符,并且设置绘制形式为粗体
        Brush brush = null;//绘制验证码的brush对象
        Color brushcolor = new Color();//绘制验证码文字的颜色
        string checkcode = string.Empty;//整个显示给用户的验证字符串
        string code = string.Empty;//当前要绘制的验证码字符
        //要生成的
        Bitmap image = new Bitmap(60,22);//图片的大小设置
        Graphics g = Graphics.FromImage(image);
        g.Clear(Color.White);
        //生成随机数的类
        Random random = new Random();
        for (int i = 0; i < 4; i++)
        {
            //DateTime.Now.Millisecond 表示服务器当前时间的毫秒部分
            //采用模运算之后保证current不会超过验证码字集合的长度
            int current = random.Next(DateTime.Now.Millisecond) % length;
            code = checkCodeString.Substring(current, 1);//从验证码字符集合中随机截取一个字符绘制
            checkcode = checkcode + code;
            brushcolor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));//随机生成绘制验证码字符的颜色
            brush= new SolidBrush(brushcolor);
            g.DrawString(code, font, brush, i * 15 + 2, 2);
        }
        Response.Clear();
        Response.ContentType = "image/pjpeg";
        image.Save(Response.OutputStream, ImageFormat.Jpeg);//将图象保存到Response的输出流中
        Session["CheckCode"] = checkcode;
        image.Dispose();
        Response.End();
    }
}

 

 

//设置登陆时验证验证码:
protected void btnok_Click(object sender, EventArgs e)
    {
        string checkcode = (string)Session["CheckCode"];
        if(checkcode.ToUpper()==txbck.Text.ToUpper())
        {
            if(txbuser.Text.Trim() != string.Empty)
            {
                Response.Redirect("default2.aspx");
               // Response.Write("<script>alert('登陆成功!')</script>");
            }
            else
            {
                this.lblmgs.Visible = true;
                this.lblmgs.Text = "用户名或密码错误!";
                //Response.Write("<script>alert('用户名或密码错误!')</script>");
            }
        }
        else
        {
            this.lblmgs.Visible = true;
            this.lblmgs.Text = "验证码错误!";
            //Response.Write("<script>alert('验证码错误!')</script>");           
        }          
      
    }

原创粉丝点击