• asp.net 验证码


    Before proceeding with the topic first we must understand "What is a Captcha code?" and "Why do we use them?". Most web sites have a Captcha validation in their sites.

    What is the Captcha code?

    A Captcha code is simply a combination of some characters and numbers like "Alk13" or "aTu2eP" etc.

    Why do we use them?

    We use them for validating that the client browser window really has a human typing into it.

    Ok, let's get to the topic i.e. creating your own Captcha code in ASP.Net.

    Step 1

    Go to Visual Studio and create a new project (web site or web application) say "CaptchCode".

    Step 2

    Now add a new page into your application say "ShowCaptcha.aspx" and add this code into the source for the page:

    <div>
    <table>
      <tr>
        <td>
          <asp:Image ID="imgCaptcha" runat="server" ImageUrl="~/CreateCaptcha.aspx?New=1"/>
         </td>
       </tr>
       <tr>
        <td>
          <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>
         </td>
        </tr>
        <tr>
         <td>
           <asp:Label ID="lblMessage" runat="server"></asp:Label>
          </td>
         </tr>
         <tr>
          <td>
     <asp:Button ID="btnCaptcha" runat="server" Text="Validate Cpatcha Code"                              onclick="btnCaptcha_Click" />
          </td>
           </tr>
         </table>
        </div>

    Note: Here I am given the ImageUrl="~/CreateCaptcha.aspx?New=1" of the image control. In CreateCaptcha.aspx we will write the code for creating the Captcha code.

    Step 3

    Now add a new page into your application "CreateCaptcha.aspx" and create the following methods in its .cs file:

    /// <summary>
    
    /// method for create captcha image
    
    /// </summary>
    
     private void CreateCaptchaImage()
    
    { 
    
     code = GetRandomText();
    
     Bitmap bitmap = new Bitmap(200, 60, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    
     Graphics g = Graphics.FromImage(bitmap);
    
     Pen pen = new Pen(Color.Yellow);
    
     Rectangle rect = new Rectangle(0, 0, 200, 60);
    
     SolidBrush blue = new SolidBrush(Color.CornflowerBlue);
    
     SolidBrush black = new SolidBrush(Color.Black);
    
     int counter = 0;
    
     g.DrawRectangle(pen, rect);
    
     g.FillRectangle(blue, rect);
    
     
    
     for (int i = 0; i < code.Length; i++)
    
     {
    
        g.DrawString(code[i].ToString(), new Font("Tahoma", 10 + rand.Next(15, 20), FontStyle.Italic), black, newPointF(10 + counter, 10));
    
       counter += 28;
    
     }
    
     DrawRandomLines(g);          
    
     bitmap.Save(Response.OutputStream, ImageFormat.Gif);
    
     g.Dispose();
    
     bitmap.Dispose();
    
     
    
    }
    
     
    
    /// <summary>
    
    /// Method for drawing lines
    
    /// </summary>
    
    /// <param name="g"></param>
    
    private void DrawRandomLines(Graphics g)
    
    {
    
       SolidBrush yellow = new SolidBrush(Color.Yellow);
    
       for (int i = 0; i < 20; i++)
    
       {g.DrawLines(new Pen(yellow, 1), GetRandomPoints());}
    
     
    
    }
    
     
    
    /// <summary>
    
    /// method for gettting random point position
    
    /// </summary>
    
    /// <returns></returns>
    
    private Point[] GetRandomPoints()
    
    {
    
      Point[] points = { new Point(rand.Next(0, 150), rand.Next(1, 150)), new    Point(rand.Next(0, 200), rand.Next(1, 190)) };
    
      return points;
    
    }
    
      
    
    /// <summary>
    
    /// Method for generating random text of 5 cahrecters as captcha code
    
    /// </summary>
    
    /// <returns></returns>
    
    private string GetRandomText()
    
    {
    
      StringBuilder randomText = new StringBuilder();          
    
      string alphabets = "012345679ACEFGHKLMNPRSWXZabcdefghijkhlmnopqrstuvwxyz";
    
      Random r = new Random();
    
      for (int j = 0; j <= 5; j++)
    
      {randomText.Append(alphabets[r.Next(alphabets.Length)]);}
    
        Session["CaptchaCode"] = randomText.ToString();
    
         return Session["CaptchaCode"] as String;
    
      }


    Step 4 

    To validate the Captcha code in the "ShowCaptcha.aspx.cs" page:
     

    protected void btnCaptcha_Click(object sender, EventArgs e)
    
    {
    
       //imgCaptcha.ImageUrl = "~/CreateCaptcha.aspx?New=0";
    
      if (Session["CaptchaCode"] != null && txtCaptcha.Text == Session["CaptchaCode"].ToString())
    
      {
    
         lblMessage.ForeColor = Color.Green;
    
         lblMessage.Text = "Captcha code validated successfully!!";
    
      }
    
      else
    
      {
    
       lblMessage.ForeColor = Color.Red;
    
       lblMessage.Text = "Captcha code is wrong!!";
    
      }
    
    }


    I hope this article will be helpful for you.

    Happy Coding!!

    附代码:下载

  • 相关阅读:
    关于 Wordpress安装时出现“Warning: Cannot modify header information – headers already sent by….”
    C#、.Net经典面试题集锦(二)
    .net 中的事务总结
    什么是webservice
    Web Service与 .NET Remoting
    动态语句exec与sp_executesql执行计划区别
    SQL2005以上版本派生表更新
    清理sql server 2005 服务器名称列表
    如何卸载VS2008
    [怎樣處理]SQL2008、SQL2005類型判斷出錯
  • 原文地址:https://www.cnblogs.com/shuaixf/p/3504616.html
Copyright © 2020-2023  润新知