SoFunction
Updated on 2025-03-01

Understand the process of generating verification codes in C#

This example introduces the detailed process of generating verification codes for your reference. The specific content is as follows

The class that generates the verification code:

using System;
using ;
using ;
using ;

namespace 
{
  /// <summary>
  /// Verification code  /// </summary>
  public class VerifyCodeHelper : AdminBaseController
  {
    #region variable    /// <summary>
    /// Color chart    /// </summary>
    private static Color[] colors = new Color[]{
      (220,20,60),
      (128,0,128),
      (65,105,225),
      (70,130,180),
      (46,139,87),
      (184,134,11),
      (255,140,0),
      (139,69,19),
      (0,191,255),
      (95,158,160),
      (255,20,147),
      (255,165,0)};

    /// <summary>
    /// Font table    /// </summary>
    private static string[] fonts = new string[] { 
      "Arial",
      "Verdana", 
      "Georgia", 
      "Bold" };

    /// <summary>
    /// Font size    /// </summary>
    private static int fontSize = 22;
    #endregion

    #region Generate verification code pictures    /// <summary>
    /// Generate verification code picture    /// </summary>
    public static Bitmap CreateVerifyCodeBmp(out string code)
    {
      int width = 120;
      int height = 40;
      Bitmap bmp = new Bitmap(width, height);
      Graphics g = (bmp);
      Random rnd = new Random();

      //Background color      (new SolidBrush(), new Rectangle(0, 0, width, height));

      //Word      StringBuilder sbCode = new StringBuilder();
      for (int i = 0; i < 4; i++)
      {
        string str = GetChar(rnd);
        Font font = GetFont(rnd);
        Color color = GetColor(rnd);
        (str, font, new SolidBrush(color), new PointF((float)(i * width / 4.0), 0));
        (str);
      }
      code = ();

      //Noise line      for (int i = 0; i < 10; i++)
      {
        int x1 = ();
        int x2 = ();
        int y1 = ();
        int y2 = ();

        Pen p = new Pen(GetColor(rnd), 1);
        (p, x1, y1, x2, y2);
      }

      //distortion      bmp = TwistImage(bmp, true, 3, () *  * 2);
      g = (bmp);

      //Noise      for (int i = 0; i < 100; i++)
      {
        int x1 = ();
        int y1 = ();

        Pen p = new Pen(GetColor(rnd), 1);
        (p, x1, y1, 1, 1);
      }

      //frame      (new Pen(new SolidBrush((153, 153, 153))), new Rectangle(0, 0, width - 1, height - 1));

      return bmp;
    }
    #endregion

    #region Get random characters    /// <summary>
    /// Get random characters    /// </summary>
    private static string GetChar(Random rnd)
    {
      int n = (0, 61);
      if (n <= 9)
      {
        return ((char)(48 + n)).ToString();
      }
      else if (n <= 35)
      {
        return ((char)(65 + n - 10)).ToString();
      }
      else
      {
        return ((char)(97 + n - 36)).ToString();
      }
    }
    #endregion

    #region Get random fonts    /// <summary>
    /// Get random fonts    /// </summary>
    private static Font GetFont(Random rnd)
    {
      return new Font(fonts[(0, )], fontSize, );
    }
    #endregion

    #region Get random colors    /// <summary>
    /// Get random colors    /// </summary>
    private static Color GetColor(Random rnd)
    {
      return colors[(0, )];
    }
    #endregion

    #region Sine Curve Wave twisted pictures    /// <summary>  
    /// Sine curve Wave twisted picture (Edit By)    /// </summary>  
    /// <param name="srcBmp">Picture path</param>    /// <param name="bXDir">Select as True if distorted</param>    /// <param name="nMultValue">The amplitude multiple of the waveform, the greater the degree of distortion, generally 3</param>    /// <param name="dPhase">The starting phase of the waveform, value interval [0-2*PI)</param>    private static  TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
    {
       destBmp = new Bitmap(, );

      // Fill the bitmap background as white       graph = (destBmp);
      (new SolidBrush(), 0, 0, , );
      ();

      double dBaseAxisLen = bXDir ? (double) : (double);

      for (int i = 0; i &lt; ; i++)
      {
        for (int j = 0; j &lt; ; j++)
        {
          double dx = 0;
          dx = bXDir ? ( * 2 * (double)j) / dBaseAxisLen : ( * 2 * (double)i) / dBaseAxisLen;
          dx += dPhase;
          double dy = (dx);

          // Get the color of the current point          int nOldX = 0, nOldY = 0;
          nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
          nOldY = bXDir ? j : j + (int)(dy * dMultValue);

           color = (i, j);
          if (nOldX &gt;= 0 &amp;&amp; nOldX &lt; 
           &amp;&amp; nOldY &gt;= 0 &amp;&amp; nOldY &lt; )
          {
            (nOldX, nOldY, color);
          }
        }
      }

      return destBmp;
    }
    #endregion

  }
}

Verification code page Action:

public ActionResult VerifyCode()
{
  string code;
  Bitmap bmp = (out code);
  Bitmap newbmp = new Bitmap(bmp, 108, 36);
  ["VerifyCode"] = code;

  ();
   = "image/bmp";
  (, );

  return View();
}

Note: The front-end page is an empty cshtml page, and the verification code value is placed in the Session.

Pages using verification code:

The img showing the verification code:

<img src="" alt="verification code" style="vertical-align: middle;" />
After the page is loaded, the verification code is displayed (note that you need to add a timestamp, otherwise the verification code will not be refreshed when refreshing the page):

$(function () {
  //Refresh the verification code  $("#refreshVerifyCode").click(function () {
    refreshVerifyCode(); //Refresh the verification code  });
  $("#verifyCode").click(function () {
    refreshVerifyCode(); //Refresh the verification code  });
  refreshVerifyCode();
});

Refresh the verification code:

//Refresh the verification codefunction refreshVerifyCode() {
  $("#verifyCode").attr("src", "VerifyCode?t=" + new Date().valueOf());
}
 

Action to determine whether the text entered by the user is the same as the verification code:

public ActionResult CheckVCode(string vcode)
{
  if (["VerifyCode"].ToString().ToLower() == ())
  {
    Dictionary<string, object> dic = new Dictionary<string, object>();
    dic["ok"] = true;
    return Content((dic));
  }
  else
  {
    Dictionary<string, object> dic = new Dictionary<string, object>();
    dic["ok"] = false;
    return Content((dic));
  }
}

The above is all about this article. I hope it will be helpful for everyone to learn how to generate verification codes in C#.