裡如何產生驗證碼asp.net

來源:互聯網
上載者:User

今天上網搜了搜怎麼來產生驗證碼,例子好多的,看了一篇文章,有了一個大概的瞭解

我對 .net 的類 如BitMap 還不太瞭解,只能根據別人的來做了。他是用 VB .net 來做的,俺不會 VB.net ,只能用 C# 了。

首先建立一個 Web 項目,完成後建立一個Web Form,名為 Gif.aspx

建一方法

private void createPic(string str)
  {
   System.Drawing.Bitmap bmp;
   System.Drawing.Graphics g;
   System.IO.MemoryStream ms;

// 還不明白為什麼要這樣做,一會再看看教程

   int picLen=str.Length*12;

   bmp=new Bitmap(picLen,20);
   g=System.Drawing.Graphics.FromImage(bmp);
   g.DrawString(str,(new Font("Arial",12)),(new SolidBrush(Color.Blue)),1,1);

   ms=new System.IO.MemoryStream();
   bmp.Save(ms,ImageFormat.Png);
   Response.ClearContent();
   Response.ContentType="image/png";
   Response.BinaryWrite(ms.ToArray());

   g.Dispose();
   bmp.Dispose();
   Response.End();

  }

做一個產生隨機數的方法

private string createRandomiz(int n)
  {
   System.Random r=new Random();
   string str="0,1,2,3,4,5,6,7,8,9,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
   char[] a=new char[1];
   a[0]=',';

   string[] str1=str.Split(a);
   string temp="";
   for ( int i=0 ;i<n;i++)
   {
   
    temp=temp+str1[r.Next(35)].ToString();

   }
   return temp;
  }

 

然後在 page_load 裡調用就行了
private void Page_Load(object sender, System.EventArgs e)
  {
   string num=this.createRandomiz(4);   // 產生 4 個隨機數
   Session["a"]=num;           //這裡用 Session 來儲存
   this.createPic(num);
  }

在 WebForm1 裡加一個 image 的 網頁伺服器控制項  將 imageUrl 設為 gif.aspx
拖放一個 button 和一個 TextBox
在 Button 裡寫

if (  this.TextBox1.Text !=Session["a"].ToString())
{
        Response.Write("error");
}
else
{
       Response.Write("ok");
}

 

這樣就完成了,繼續看教程了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.