Home Backend Development C#.Net Tutorial Detailed explanation of examples of asp.net click verification code

Detailed explanation of examples of asp.net click verification code

May 08, 2017 am 09:26 AM

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;
  }
Copy after login

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;
  }
Copy after login

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;
  }
Copy after login

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;
  }
Copy after login

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);
  }
Copy after login

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);
  }
Copy after login

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>
Copy after login

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>
Copy after login

[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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Apr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Apr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

Is C# .NET Right for You? Evaluating its Applicability Is C# .NET Right for You? Evaluating its Applicability Apr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# as a Versatile .NET Language: Applications and Examples C# as a Versatile .NET Language: Applications and Examples Apr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

See all articles