自己動手做驗證碼 .net

來源:互聯網
上載者:User

   今天學了下如何做驗證碼。

   下面說下簡單的步驟

1.   建立一個validate.ashx頁面,把 ProcessRequest(HttpContext context)的函數體換成一下內容。

            context.Response.ContentType = "image/jpeg";

            using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(100, 40))

            {

                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))

                {

                    Random rand = new Random();

                    int code = rand.Next(1000, 9999);

                    string strCode=code.ToString();

                    // 如果要讓一般處理常式使用Session,必須實現System.Web.SessionState.IRequiresSessionState介面

                    HttpContext.Current.Session["code"]=strCode;

                    g.DrawString(strCode,new System.Drawing.Font("宋體",30),System.Drawing.Brushes.Green,new System.Drawing.PointF(0,0));

                    System.Drawing.Pen pen = (System.Drawing.Pen)System.Drawing.Pens.Red.Clone();

                    g.DrawLine(pen, new System.Drawing.Point(10, 10), new System.Drawing.Point(20, 20));

                    bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

                }

            }

 

上面代碼主要用了點GUI的知識,不必深入研究,略知即可。

 

2.  建立一個Validate.aspx頁面,然後再其中<div></div>中,添加一個<img />,使其src屬性為第一步中所建頁面名稱。 如果

     想要點擊片就換一下驗證碼的話,就可以為<img />加上一個onclick事件使其重新指向第一步中所建頁面。    

     onclick="this.src='validate.ashx'"

 

3.  然後運行下第二步中所建頁面,就能看到效果。接著在Validate.aspx中添加一個TextBox和一個Button,Button的click響

    應函數體如下:

            string txtVal = txtValidate.Text;

            if (Session["code"].ToString() == txtVal)

            {

                Response.Write("登入成功!");

            }

            else

            {

                Response.Write("登入失敗!");

            }

4. 好了,結束了。可以運行下Validate.aspx頁面,查看下效果。簡單吧?但是有個問題,你試一試就知道了。

 

5. 其實上面還是有個問題的。<img /> onclick事件中,我們把this.src重新賦值為validate.ashx,原本是想讓它重新向伺服器請求,

    伺服器重建一個驗證碼顯示。但是關鍵是,我們傳過去的仍然是validate.ashx這個頁面,當伺服器檢測到傳來的頁面還是原

    來的頁面時,它並不會對此作出響應。所以我們上面所做的驗證碼仍然無法實現點擊下就切換這個效果。對此問題有個方法可以解決。

    就是在validate.ashx傳給伺服器時我們給加上一些參數,但是參數得每次都不一樣。根據這個思路,可以js中的隨機數來產生參數,

    也可以用個時間函數解決問題。我就用個時間函數解決了,圖個方便而已。把<img /> onclick事件改成"this.src='validate.ashx?    

    aaa='+new Date()"。 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.