Home  >  Article  >  Backend Development  >  Detailed explanation of examples of asp.net click verification code

Detailed explanation of examples of asp.net click verification code

Y2J
Y2JOriginal
2017-05-08 09:26:271632browse

This article mainly introduces the sharing of ideas for asp.net click verification code implementation (with demo), which has certain reference value. Interested friends can refer to it.

Haha, it hasn’t been posted for a long time. Finally, I saw that the click verification code was interesting, so I wanted to write one myself.

First the renderings

If you are attracted by this effect, please continue reading.

Let me give you some ideas before posting the code:

1. There must be a Chinese character library and classify it according to glyphs. (I classified the radicals in the database)

2. Get the verification code (that is, take a few characters to make the verification code)

3. Take it out based on Find the words with similar shapes

4. Arrange the verification code text and the words with similar shapes

5. Draw the picture

6. Display

1. Obtain the character library

#Our country’s culture is profound and profound, where do so many spicy characters come from? Of course, I couldn't add it manually, so I randomly found a website that could look up Chinese characters on the Internet to capture other people's data. To capture data, please click on the portal. What is mentioned in the portal is just ideas. If there is anything you don’t understand, please tell me. I'll share my font library below.

2. Get the verification code

This is relatively simple. I will paste the code directly here. The following code is randomly sorted and obtained. 4 pieces of data, I write them like this for convenience. Personally, I feel that the ID is randomly generated first, and then the data is fetched directly based on the ID, so that the query speed will be faster than the following writing method. (Note that the database I use is MySql)

  /// <summary>
  /// 获取验证码
  /// </summary>
  public List<VerificationCode.Model.WenZhi> GetCodeText()
  {
   const string sql = "SELECT * FROM wenzhi ORDER BY RAND() LIMIT 4";
   var dataReader = dbHelper.GetDataReader(sql);
   var list = DataReaderToList(dataReader);
   dataReader.Close();
   return list;
  }

3. Find similar words based on the extracted text

Because In the first step, I saved the radical, so here I directly get the closest character of the current radical based on the radical.

  /// <summary>
  /// 获取答案备选
  /// </summary>
  /// <param name="buShouCode">部首编码</param>
  /// <param name="id">当前文字ID</param>
  /// <param name="number">数量</param>
  /// <returns></returns>
  public List<VerificationCode.Model.WenZhi> GetAnswer(string buShouCode, int id,int number=1)
  {
   string sql = $"SELECT * FROM wenzhi where BuShouCode=&#39;{buShouCode}&#39; and ID <> {id} ORDER BY RAND() LIMIT "+ number;
   var dataReader = dbHelper.GetDataReader(sql);
   var list = DataReaderToList(dataReader);
   dataReader.Close();
   return list;
  }

4. Arrange the verification code text and similar words

The following code first puts the alternative answers and verification codes in a set and then Sort the collection

 public Model.Code GetCode()
  {
   
   var wenzlist = _wenZhiDal.GetCodeText(); //获取验证码
   var listAnsuwr = new List<Answer>();//实例化备选答案对象
   var answerCode = string.Empty;//答案
   var result = new Model.Code
   {
    Id = Guid.NewGuid().ToString()
   };
   //根据验证码获取备选答案并把添加到答案添加到备选答案集合
   foreach (var item in wenzlist)
   {
    answerCode += item.ID + ",";
    result.AnswerValue += item.Text;
    var answerList = _wenZhiDal.GetAnswer(item.BuShouCode, item.ID);
    listAnsuwr.Add(new Answer { Id = item.ID.ToString(), Img = GetImage(item.Text) });
    listAnsuwr.AddRange(answerList.Select(answer => new Answer { Id = answer.ID.ToString(), Img = GetImage(answer.Text) }));
   }
   //如果答案个数不够就再去取几个
   if (listAnsuwr.Count < 9)
   {
    var ran = new Random();
    var randKey = ran.Next(0, 4);
    var item = wenzlist[randKey];
    var answerList = _wenZhiDal.GetAnswer(item.BuShouCode, item.ID, 9 - listAnsuwr.Count);
    listAnsuwr.AddRange(answerList.Select(answer => new Answer { Id = answer.ID.ToString(), Img = GetImage(answer.Text) }));
   }
   result.CodeImg = GetImage(result.AnswerValue);//获取图片
   result.AnswerValue = answerCode.TrimEnd(&#39;,&#39;);
   result.Answer = RandomSortList(listAnsuwr);//打乱正确答案与形近字的顺序
   return result;
  }

This is the code for sorting the collection

  /// <summary>
  /// 随机排列集合
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="listT"></param>
  /// <returns></returns>
  private static List<T> RandomSortList<T>(IEnumerable<T> listT)
  {
   var random = new Random();
   var newList = new List<T>();
   foreach (var item in listT)
   {
    newList.Insert(random.Next(newList.Count + 1), item);
   }
   return newList;
  }

5. Draw the picture

The following is the code for drawing the picture, verify The code and alternative answers correspond to two different drawing methods (notes are written quite clearly). Don’t worry that humans can’t tell the difference after the text is rotated x°, haha. In the last sentence of the code, I converted the image to Base64 to facilitate front-end calling.

private static string GetImage(string text)
  {
   Image image;
   switch (text.Length)
   {
    case 1:
     image = new Bitmap(50, 40);
     break;
    case 4:
     image = new Bitmap(120, 40);
     break;
    default:
     image = new Bitmap(50, 40);
     break;
   }
   Brush brushText = new SolidBrush(Color.FromArgb(255, 0, 0, 0));
   var graphics = Graphics.FromImage(image);
   graphics.SmoothingMode = SmoothingMode.AntiAlias;
   graphics.Clear(Color.White);
   var font = new Font(new FontFamily("华文彩云"), 20, FontStyle.Regular);
   if (text.Length > 1)//画验证码
   {
    //先来两条直线做干扰 然后再画文字
    graphics.DrawLine(new Pen(brushText, new Random().Next(1, 3)), new Point(new Random().Next(0, 10), new Random().Next(10, 40)), new Point(new Random().Next(100, 120), new Random().Next(10, 30)));
    graphics.DrawLine(new Pen(brushText, new Random().Next(1, 3)), new Point(new Random().Next(20, 50), new Random().Next(0, 10)), new Point(new Random().Next(100, 120), new Random().Next(30, 40)));
    graphics.DrawString(text, font, brushText, 0, 10);

   }
   else//画备选答案
   {
    Point middle = new Point(25, 20);
    graphics.TranslateTransform(middle.X, middle.Y);
    //这里是360°随机旋转 
    graphics.RotateTransform(new Random().Next(0, 360));
    var format = new StringFormat(StringFormatFlags.NoClip)
    {
     Alignment = StringAlignment.Center,
     LineAlignment = StringAlignment.Center
    };
    graphics.DrawString(text, font, brushText, 0, 0, format);

   }
   brushText.Dispose();
   graphics.Dispose();
   return ImageToBase64(image);
  }

6. Display

You can return the verification code object by directly calling the GetCode method

The following is the background code, which should be The correct answer is placed in AnswerValue, so I first take it out and put it in Session, then clear the value and then return it to the browser through json.

  public string GetVerCode()
  {
   var code = new VerificationCode.Code().GetCode();
   Session["VERCODE"] = code.AnswerValue;
   code.AnswerValue = "";
   return JsonConvert.SerializeObject(code);
  }

Now let’s pile up some html code

<p class="form-group">
     <ul class="vercode">
      <li><img src=&#39;&#39;/></li>
      <li><img src=&#39;&#39;/></li>
      <li><img src=&#39;&#39;/></li>
      <li><img src=&#39;&#39;/></li>
      <li class="delete" onclick="delete_input()"></li>
     </ul>
     <p>
      <img id="code-image"/> <a href="javascript:void(0);" onclick="load_vercode()">看不清?</a>
     </p>
     <ul class="vercode-anwser">
      <li><img /></li>
      <li><img /></li>
      <li><img /></li>
      <li><img /></li>
      <li><img /></li>
      <li><img /></li>
      <li><img /></li>
      <li><img /></li>
      <li><img /></li>
     </ul>
    </p>

Let’s add some js code. Here we only realize the effect on the picture, and we haven’t verified the data yet (here is the verification idea: each picture corresponds to An ID, get the ID of the selected picture separated by commas, and then compare it with the value in Session)

<script>
  $(function () {
   //加载验证码
   load_vercode();
   //绑定验证码点击事件
   $(".vercode-anwser").find("img").on("click", null, function () {
    $(".vercode").find("img[src=&#39;&#39;]:eq(0)").attr("src", $(this).attr("src"));
   });
  });

  function load_vercode() {
   $(".vercode").find("img").attr("src", "");
   $.get("GetVerCode", function (data) {
    var result = JSON.parse(data);
    $("#code-image").attr("src", "data:image/png;base64," + result.CodeImg);
    $(".vercode-anwser").find("img").each(function (index) {
     $(this).attr("src", "data:image/png;base64," + result.Answer[index].Img);
    });
   });
  }
  //删除事件
  function delete_input() {
   $(".vercode").find("img[src!=&#39;&#39;]:last").attr("src", "");
  }
 </script>

[Related recommendations]

1.ASP free video tutorial

2.ASP tutorial

3.Li Yanhui ASP basic video tutorial

The above is the detailed content of Detailed explanation of examples of asp.net click verification code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn