Home > Backend Development > C#.Net Tutorial > How to generate and use .net verification code

How to generate and use .net verification code

高洛峰
Release: 2017-01-13 15:02:59
Original
1496 people have browsed it

Small Classroom: The role of verification code:

A few years ago, most websites, forums and the like did not have verification codes, because for ordinary users, verification codes only increased user operations. Reduced user experience. However, various spamming robots, voting robots, and malicious registration robots emerged in an endless stream, which greatly increased the burden on the website and also brought a large amount of junk data to the website database. In order to prevent the destruction of various robot programs, programmers came up with verification codes that can only be recognized by the human eye and are not easily recognized by programs!

The verification code is a picture, with letters, numbers and even Chinese characters as the content of the picture. In this way, the content in the picture is easy to identify with the human eye, but the program will not be able to identify it. Before performing database operations (such as login verification, voting, posting, replying, registration, etc.), the program first verifies whether the verification code submitted by the client is the same as the content in the picture. If it is the same, it will perform the database operation. If it is different, it will prompt a verification code error. , no database operations are performed. In this way, all kinds of robot programs will be blocked!

But with the development of computer science, technologies such as pattern recognition are becoming more and more mature, so the guy who writes the robot program can recognize the content written directly in the picture through the program, and then submit it to the server for verification. The code will be useless. In order to prevent the recognition of robot programs, the image generation of verification codes is also constantly evolving, adding interference points, interference lines, text deformation, changing angle positions, different colors... Various technologies to prevent computer recognition are also applied to verification codes. In the competition between these two technologies, the verification code we see now is formed. Many people are already complaining, "What kind of verification code is this? The human eye can't tell what it is." Everything is helpless.

Understanding the function of the verification code, let’s write a simple example of generating and using the verification code

How to generate and use .net verification code

First create a page to display the verification code and Determine whether the verification code input is correct

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 <script type="text/javascript">
 //点击切换验证码
 function f_refreshtype() {
 var Image1 = document.getElementById("img");
 if (Image1 != null) {
 Image1.src = Image1.src + "?";
 }
 } 
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <table>
 <tr>
 <td>
  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
 </td>
 <td>
  <img  src="png.aspx" id="img" onclick="f_refreshtype()" / alt="How to generate and use .net verification code" >
 </td>
 <td>
  <asp:Button ID="Button1" runat="server" Text="确定" />
 </td>
 </tr>
 </table>
 </div>
 </form>
</body>
</html>
Copy after login

The verification code is verified in the background of this page

protected void Page_Load(object sender, EventArgs e)
{
//生成的验证码被保存到session中
if (Session["CheckCode"] != null)
{
string checkcode = Session["CheckCode"].ToString();
if (this.TextBox1.Text == checkcode)
{
 ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert(&#39;验证码输入正确!&#39;)", true);
}
else
{
 ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert(&#39;验证码输入错误!&#39;)", true);
}
}
 
}
Copy after login

Generate verification code page png.aspx

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateCheckCodeImage(GenerateCheckCodes(4));
}
}
public void ShowAuthCode(Stream stream, out string code)
{
Random random = new Random();
code = random.Next(1000, 9999).ToString();
 
Bitmap bitmap = CreateAuthCode(code);
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
}
 
private string GenerateCheckCodes(int iCount)
{
int number;
string checkCode = String.Empty;
int iSeed = DateTime.Now.Millisecond;
System.Random random = new Random(iSeed);
for (int i = 0; i < iCount; i++)
{
number = random.Next(10);
checkCode += number.ToString();
}
Session["CheckCode"] = checkCode;
return checkCode;
}
 
private Bitmap CreateAuthCode(string str)
{
Font fn = new Font("宋体", 12);
Brush forecolor = Brushes.Black;
Brush bgcolor = Brushes.White;
PointF pf = new PointF(5, 5);
Bitmap bitmap = new Bitmap(100, 25);
Rectangle rec = new Rectangle(0, 0, 100, 25);
Graphics gh = Graphics.FromImage(bitmap);
gh.FillRectangle(bgcolor, rec);
gh.DrawString(str, fn, forecolor, pf);
return bitmap;
}
 
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
int iWordWidth = 15;
int iImageWidth = checkCode.Length * iWordWidth;
Bitmap image = new Bitmap(iImageWidth, 20);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器 
Random random = new Random();
//清空图片背景色 
g.Clear(Color.White);
 
//画图片的背景噪音点
for (int i = 0; i < 20; 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);
}
 
//画图片的背景噪音线 
for (int i = 0; i < 2; i++)
{
 int x1 = 0;
 int x2 = image.Width;
 int y1 = random.Next(image.Height);
 int y2 = random.Next(image.Height);
 if (i == 0)
 {
 g.DrawLine(new Pen(Color.Gray, 2), x1, y1, x2, y2);
 }
 
}
 
 
for (int i = 0; i < checkCode.Length; i++)
{
 
 string Code = checkCode[i].ToString();
 int xLeft = iWordWidth * (i);
 random = new Random(xLeft);
 int iSeed = DateTime.Now.Millisecond;
 int iValue = random.Next(iSeed) % 4;
 if (iValue == 0)
 {
 Font font = new Font("Arial", 13, (FontStyle.Bold | System.Drawing.FontStyle.Italic));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Red, 1.5f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 1)
 {
 Font font = new System.Drawing.Font("楷体", 13, (FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.DarkRed, 1.3f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 2)
 {
 Font font = new System.Drawing.Font("宋体", 13, (System.Drawing.FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Green, Color.Blue, 1.2f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 3)
 {
 Font font = new System.Drawing.Font("黑体", 13, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Green, 1.8f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
}
//////画图片的前景噪音点 
//for (int i = 0; i < 8; i++)
//{
// int x = random.Next(image.Width);
// int y = random.Next(image.Height);
// image.SetPixel(x, y, Color.FromArgb(random.Next()));
//}
//画图片的边框线 
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
Copy after login

More.net verification code generation and Please pay attention to the PHP Chinese website for articles related to usage methods!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template