Detailed asp.net verification code generation method _ Practical skills

Source: Internet
Author: User

General verification code generation methods are the same, the main step is two steps

The first step : Random out of a system verification code numbers or letters, and randomly generated numbers or letters to write cookies or session.

Step two : Use the first step of the random numbers or letters to synthesize the picture.

You can see that the complexity of the verification code is mainly the second step to complete, you can according to the complexity of their own to set.

Let's look at it together:

The first step: the method of randomly generating numbers or letters

<summary>
  ///Generate verification Code random number
  ///</summary>
  ///<returns> return five-bit random number </returns>
  private string Generatecheckcode ()
  {
    int number;
    char code;
    string checkcode = String.Empty;

    Random Random = new Random ();

    for (int i = 0; i < 5; i++)//You can set any number of digits = random that generate the verification code
      . Next ();

      if (number% 2 = 0)
        code = (char) (' 0 ' + (char) (number%));
      else
        code = (char) (' A ' + (char) (number%));

      Checkcode + = code. ToString ();
    }

    RESPONSE.COOKIES.ADD (New HttpCookie ("Checkcode", Checkcode))//write Cookis session[
    "checkcode"] = Checkcode;// Write session, you can choose any return
    Checkcode;
  

Step Two: Generate pictures

<summary>///Generate verification code picture///</summary>///<param name= "Checkcode" ></param> private Voi

    D createcheckcodeimage (String checkcode) {if (Checkcode = null | | | Checkcode.trim () = = String.Empty) return;
    Bitmap image = new Bitmap ((int) math.ceiling (Checkcode.length * 12.5)), 22;

    Graphics g = graphics.fromimage (image);

      try {//Generate a random generator Random Random = new Random ();

      Clear the picture background color g.clear (color.white); The background noise line for the picture is for (int i = 0; i < i++) {int x1 = random. Next (image.
        Width); int x2 = random. Next (image.
        Width); int y1 = random. Next (image.
        Height); int y2 = random. Next (image.

        Height);
      G.drawline (New Pen (color.silver), x1, y1, x2, y2); Font font = new System.Drawing.Font (Arial), (System.Drawing.FontStyle.Bold |
      System.Drawing.FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush (new Rectangle (0, 0, image. WidTh, image.
      Height), Color.Blue, color.darkred, 1.2f, true);

      g.DrawString (Checkcode, Font, brush, 2, 2); Picture foreground noise point for (int i = 0; i < i++) {int x = random. Next (image.
        Width); int y = random. Next (image.

        Height); Image. SetPixel (x, Y, Color.FromArgb) (random.
      Next ())); ///Draw the picture's border line G.drawrectangle (new Pen (Color.silver), 0, 0, image. Width-1, image.

      HEIGHT-1);
      MemoryStream ms = new MemoryStream (); Image.
      Save (MS, SYSTEM.DRAWING.IMAGING.IMAGEFORMAT.GIF);
      Response.clearcontent ();
      Response.ContentType = "Image/gif"; Response.BinaryWrite (Ms.
    ToArray ());
      finally {//Release object resource G.dispose (); Image.
    Dispose ();

 }

* Complete Program

First add a checkcode.aspx file to the project inside the VS2005 and add the following complete code to the CheckCode.aspx.cs code file

Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Drawing;
Using System.IO;

Using System.Drawing.Drawing2D; Public partial class CheckCode:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {creat
  Echeckcodeimage (Generatecheckcode ());//Call the following two methods; ///<summary>///Generate verification Code random number///</summary>///<returns> return five-bit random number </returns> private str
    ing Generatecheckcode () {int number;
    char code;

    string checkcode = String.Empty;

    Random Random = new Random (); for (int i = 0; i < 5; i++)//You can set any number of digits = random that generate the verification code.

      Next ();
      if (number% 2 = 0) code = (char) (' 0 ' + (char) (number% 10));

      else Code = (char) (' A ' + (char) (number% 26); CheckCode = = Code.
    ToString (); } Response.Cookies.Add (New HttpCookie ("Checkcode", Checkcode))//write Cookis session["Checkcode"] = Checkcode;
  Write session, you can choose any return checkcode; ///<summary>///generate captcha picture///</summary>///<param name= "Checkcode" ></param> privat e void Createcheckcodeimage (string checkcode) {if (Checkcode = null | | Checkcode.trim () = String.Empty) ret

    Urn
    Bitmap image = new Bitmap ((int) math.ceiling (Checkcode.length * 12.5)), 22;

    Graphics g = graphics.fromimage (image);

      try {//Generate a random generator Random Random = new Random ();

      Clear the picture background color g.clear (color.white); The background noise line for the picture is for (int i = 0; i < i++) {int x1 = random. Next (image.
        Width); int x2 = random. Next (image.
        Width); int y1 = random. Next (image.
        Height); int y2 = random. Next (image.

        Height);
      G.drawline (New Pen (color.silver), x1, y1, x2, y2); } Font Font = new System.Drawing.Font ("Arial", (System.Drawing.FontStyle.Bold |
      System.Drawing.FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush (new Rectangle (0, 0, image. Width, image.
      Height), Color.Blue, color.darkred, 1.2f, true);

      g.DrawString (Checkcode, Font, brush, 2, 2); Picture foreground noise point for (int i = 0; i < i++) {int x = random. Next (image.
        Width); int y = random. Next (image.

        Height); Image. SetPixel (x, Y, Color.FromArgb) (random.
      Next ())); ///Draw the picture's border line G.drawrectangle (new Pen (Color.silver), 0, 0, image. Width-1, image.

      HEIGHT-1);
      MemoryStream ms = new MemoryStream (); Image.
      Save (MS, SYSTEM.DRAWING.IMAGING.IMAGEFORMAT.GIF);
      Response.clearcontent ();
      Response.ContentType = "Image/gif"; Response.BinaryWrite (Ms.
    ToArray ());
      finally {//Release object resource G.dispose (); Image.
    Dispose ();

 }
  }

}

The above generated verification code page is done, let's call to see:

Add the image control where you need to use the verification code.

<asp:image id= "Image1" runat= "Server" imageurl= "~/checkcode.aspx"/>

This will display the verification code above the image control!

The display is ready, of course we have to judge the user's input is correct!

As soon as we get the value of the user input, it's OK to compare Cookis or session.

take the value of cookies request.cookies["Checkcode"]. Value

take the value of the session session["Checkcode"]. ToString () (preferably to determine whether the session is empty)

If you do not differentiate between case, the value entered by the user and the value of the cookie or session are converted to uppercase or lowercase

Attach Usage

protected void Button1_Click (object sender, EventArgs e)
  {
    if (request.cookies["Checkcode"]. Value = = TextBox1.Text.Trim (). ToString ())
    {
      Response.Write ("Cookies are Right");
    }
    else
    {
      Response.Write ("Cookie is Wrong");
    }

    if (session["Checkcode"]!= null)
    {
      if (session["Checkcode"]. ToString (). ToUpper () = = TextBox1.Text.Trim (). ToString (). ToUpper ())
        //This write can not be case-sensitive
      {
        Response.Write ("Session are right");

      }
      else
      {
        Response.Write ("Session is Wrong");
      }
    }
  

The above is the whole content of this article, teach everybody how to make asp.net verification code, hope everybody likes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.