ASP.NET 验证码实现代码(C#)攻略
前言
验证码是一种常用的安全验证手段,用于防止恶意机器人注册、登录、提交表单等操作。本篇文章将介绍如何在ASP.NET中使用C#实现验证码功能。
实现过程
1. 生成随机字符串
首先,我们需要生成一串随机字符串,作为验证码。可以使用Random类和StringBuilder类来生成:
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++)
{
int code = random.Next(65, 91); // Generate the verification code with the ASCII value of A to Z
sb.Append((char)code); // Convert the ASCII code to character and append it to the StringBuilder
}
string verCode = sb.ToString();
2. 将验证码存入Session
生成验证码之后,我们需要将其存储在Session中,以便于后面的验证。可以使用如下代码:
Session["VerificationCode"] = verCode;
3. 绘制验证码图片
接下来,我们需要将验证码绘制成一张图片。可以使用GDI+绘图库,将随机字符串绘制在一张空白图片上。代码如下所示:
Bitmap bitmap = new Bitmap(100, 30); // Create an empty image with the width of 100 and the height of 30
Graphics graphics = Graphics.FromImage(bitmap); // Get the graphics object of the image
// Set the font and color of the string to be drawn
Font font = new Font("Arial", 18, FontStyle.Bold);
SolidBrush brush = new SolidBrush(Color.Black);
graphics.DrawString(verCode, font, brush, 10, 5); // Draw the string on the image
4. 输出图片
最后一步是将生成的验证码图片输出到客户端。可以将图片以二进制形式输出,如下所示:
MemoryStream ms = new MemoryStream(); // Create a memory stream to store the image
bitmap.Save(ms, ImageFormat.Jpeg); // Save the image to the memory stream in JPEG format
Response.ClearContent(); // Clear the response buffer
Response.ContentType = "image/Jpeg"; // Set the content type of the response to image/Jpeg
Response.BinaryWrite(ms.ToArray()); // Write the image to the response
示例说明
示例1: 在ASP.NET网页中使用验证码
在ASP.NET网页中使用验证码,可以防止机器人恶意注册或登录。下面是一个简单的示例,展示如何在ASP.NET网页中使用上述代码实现验证码功能:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GenerateVerificationCode(); // Generate a verification code when the page first loads
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtVerificationCode.Text.Trim().Equals(Session["VerificationCode"].ToString(), StringComparison.OrdinalIgnoreCase))
{
// Verification succeeded, do something...
}
else
{
// Verification failed, do something...
GenerateVerificationCode(); // Generate a new verification code and refresh the image
}
}
private void GenerateVerificationCode()
{
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++)
{
int code = random.Next(65, 91); // Generate the verification code with the ASCII value of A to Z
sb.Append((char)code); // Convert the ASCII code to character and append it to the StringBuilder
}
string verCode = sb.ToString();
Session["VerificationCode"] = verCode;
Bitmap bitmap = new Bitmap(100, 30); // Create an empty image with the width of 100 and the height of 30
Graphics graphics = Graphics.FromImage(bitmap); // Get the graphics object of the image
Font font = new Font("Arial", 18, FontStyle.Bold); // Set the font and color of the string to be drawn
SolidBrush brush = new SolidBrush(Color.Black);
graphics.DrawString(verCode, font, brush, 10, 5); // Draw the string on the image
MemoryStream ms = new MemoryStream(); // Create a memory stream to store the image
bitmap.Save(ms, ImageFormat.Jpeg); // Save the image to the memory stream in JPEG format
Response.ClearContent(); // Clear the response buffer
Response.ContentType = "image/Jpeg"; // Set the content type of the response to image/Jpeg
Response.BinaryWrite(ms.ToArray()); // Write the image to the response
graphics.Dispose(); // Dispose the graphics object
bitmap.Dispose(); // Dispose the bitmap object
}
示例2: 将验证码封装为ASP.NET自定义控件
将验证码封装为ASP.NET自定义控件,可以将其易于重用,并且可以更加方便地设置外观和行为。下面是一个简单的示例,展示如何将验证码封装为ASP.NET自定义控件:
public class VerificationCodeControl : WebControl, INamingContainer
{
private string _verCode;
[DefaultValue(4)]
public int Length { get; set; } = 4;
public string FontFamily { get; set; } = "Arial";
public int FontSize { get; set; } = 18;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
GenerateVerificationCode(); // Generate a verification code when the control is initialized
this.Attributes["src"] = this.Page.ResolveUrl("~/VerificationCode.ashx"); // Set the source of the image to the ASHX handler
}
private void GenerateVerificationCode()
{
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Length; i++)
{
int code = random.Next(65, 91); // Generate the verification code with the ASCII value of A to Z
sb.Append((char)code); // Convert the ASCII code to character and append it to the StringBuilder
}
_verCode = sb.ToString();
this.Page.Session["VerificationCode"] = _verCode;
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Alt, "Verification Code");
writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass);
writer.AddAttribute(HtmlTextWriterAttribute.Style, $"font-family: {FontFamily}; font-size: {FontSize}px;");
base.AddAttributesToRender(writer);
}
protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write(_verCode); // Render the verification code as plain text (fallback for non-HTML5 browser)
base.RenderContents(writer);
}
}
上述代码会生成一个继承自WebControl的VerificationCodeControl控件,可以在ASP.NET网页中方便地使用。比如,可以在ASPX页面中使用以下代码:
<%@ Register TagPrefix="Custom" Namespace="MyNamespace" %>
<Custom:VerificationCodeControl ID="VerificationCode1" runat="server" Length="6" FontSize="30" />
这里演示的是如何将生成验证码的逻辑封装为自定义控件,并且使用ASHX处理程序来输出验证码图片。稍微修改一下ASHX处理程序即可。
结语
本文介绍了如何使用C#在ASP.NET中实现验证码功能,并且提供了两个简单的示例。通过使用验证码,可以提高网站的安全性和可靠性,避免恶意机器人、蜘蛛等程序对网站造成的风险和威胁。
参考资料
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:ASP.net 验证码实现代码(C#) - Python技术站