


Detailed explanation of examples of asp.net click verification code
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='{buShouCode}' 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(','); 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=''/></li> <li><img src=''/></li> <li><img src=''/></li> <li><img src=''/></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='']: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!='']:last").attr("src", ""); } </script>
[Related recommendations]
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

A strategy to avoid errors caused by default in C switch statements: use enums instead of constants, limiting the value of the case statement to a valid member of the enum. Use fallthrough in the last case statement to let the program continue to execute the following code. For switch statements without fallthrough, always add a default statement for error handling or provide default behavior.
