验证码制作

项目前期完成了,开始着手做后台,压力小了点,有更多的时间研究新东西了

验证码并不是新东西,一直没弄明白是怎么回事,前些天用GDI忽然有了思路,就用上了

登陆页的后台代码,用Sleep放刷新延迟

  private void Page_Load(object sender, System.EventArgs e)
  {
   
if(!this.IsPostBack)
   {
    System.Threading.Thread.Sleep(
1000);
    
char[] source = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890").ToCharArray();
    
string code = "";
    Random rnd 
= new Random();
    
for (int i=0 ; i < 4 ; i++)
     code 
+= source[rnd.Next(source.Length-1)];
    Session[
"code"]=code;
   }
  }

登陆验证
        private void BtnLogin_Click(object sender, System.EventArgs e)
        {
            
if (TxtCode.Text.ToLower() != Session["code"].ToString().ToLower())
            {
                Response.Write(
"<script>alert(\"验证码错误\")</script>");
                Response.Write(
"<script>window.navigate(\"index.aspx\")</script>");
                return;
            }
            
if (TxtUserName.Text == "username" && TxtPassword.Text == "password")
            {
                Session[
"UserName"= TxtUserName.Text;
                Response.Redirect(
"下一页面");
            }
            Response.Write(
"<script>alert(\"密码错误\")</script>");
            Response.Write(
"<script>window.navigate(\"index.aspx\")</script>");
        }


前台还是用一个Img服务器对象 url为code.aspx
Code.aspx.cs如下

        private void Page_Load(object sender, System.EventArgs e)
        {
            
if(Session["code"].ToString()!="")
            {
                Bitmap bm 
= new Bitmap(60,30);
                Graphics g 
= Graphics.FromImage(bm);
                g.DrawString(Session[
"code"].ToString(),new System.Drawing.Font("宋体",20),new SolidBrush(Color.WhiteSmoke),0,0);
                bm.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);
            }
        }


OK,完成了

posted on 2005-11-30 18:00  昊子  阅读(2316)  评论(6编辑  收藏  举报

导航