ASP.net 登录验证码

来源:互联网 发布:思维方式知乎 编辑:程序博客网 时间:2024/05/18 01:21

很简单的一个程序,但是却是自己所写:

1.aspx.cs:

 private void Button1_ServerClick(object sender, System.EventArgs e)
  {
   string textValue = Text1.Value.ToString();
   if(textValue == Session["CheckCode"].ToString())
   {
    Text1.Value = "ok!";
   }
   else
   {
    Text1.Value = "wrong";
   }
  }

1.aspx

<asp:Image id="Image1" style="Z-INDEX: 101; LEFT: 536px; POSITION: absolute; TOP: 152px" runat="server"
    Width="72px" ImageUrl="ValidateCode.aspx" Height="24px"></asp:Image>

ValidateCode.aspx:

private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   string CheckCode = CreateRandomCode(4);
   CreateImage(CheckCode);
   Session["CheckCode"] = CheckCode;
  }

//生成随机码
  private string CreateRandomCode(int codeCount)
  {
   string allChar="1,2,3,4,5,6,7,8,9";
   string[] allCharArray = allChar.Split(',');
   string RandomCode = "";
   int temp = -1;
   Random rand = new Random();
   for(int i=0;i<codeCount;i++)
   {
    if(temp != -1)
    {
     int intSeed = i*temp*((int)DateTime.Now.Ticks);
     rand = new Random(intSeed);
    }
    int t = rand.Next(6);  //
    if(temp == t)
    {
     return CreateRandomCode(codeCount);
    }
    temp = t;
    RandomCode += allCharArray[t];
   }
   return RandomCode;
  }
  //生成随机码对应的图
  private void CreateImage(string CheckCode)
  {
   int iwindth = (int)(CheckCode.Length*11.5);
   System.Drawing.Bitmap Image = new Bitmap(iwindth,20);
   Graphics g = Graphics.FromImage(Image);
   Font f = new System.Drawing.Font("Arial", 8, System.Drawing.FontStyle.Regular);
   Brush b = new System.Drawing.SolidBrush(Color.Blue);
   //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
   g.Clear(Color.White);
   g.DrawString(CheckCode, f, b, 3, 3);

   Pen blackPen = new Pen(Color.Black, 0);
   Random rand = new Random();
//   for (int i=0;i<5;i++)  //生成一个随机的线条
//   {
//    int y = rand.Next(Image.Height-2);
//    g.DrawLine(blackPen,0,y,Image.Width,y);
//   }
           
   System.IO.MemoryStream ms = new System.IO.MemoryStream();
   Image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
   Response.ClearContent();
   Response.ContentType = "image/Jpeg";
   Response.BinaryWrite(ms.ToArray());
   g.Dispose();
   Image.Dispose();

  }

原创粉丝点击