C# ASP.NET登錄頁面驗證碼
时间: 2024-02-05 10:08:24 浏览: 17
根据提供的引用内容,以下是一个C# ASP.NET登录页面验证码的制作与校验的示例:
1. 在ASP.NET页面中添加一个Image控件用于显示验证码图片,并设置其ID为"imgCaptcha"。
2. 在后台代码中生成验证码图片,并将其保存到Session中以便校验。
```csharp
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string captcha = GenerateCaptcha();
Session["Captcha"] = captcha;
imgCaptcha.ImageUrl = "GenerateCaptchaImage.aspx";
}
}
private string GenerateCaptcha()
{
// 生成随机验证码
string captcha = GenerateRandomCode();
// 将验证码绘制到图片上
Bitmap image = new Bitmap(200, 80);
Graphics graphics = Graphics.FromImage(image);
graphics.DrawString(captcha, new Font("Arial", 40), Brushes.Black, new PointF(10, 10));
// 添加噪点和干扰线条
AddNoiseAndLines(graphics);
// 保存图片并返回验证码
string imagePath = Server.MapPath("~/CaptchaImages/captcha.png");
image.Save(imagePath, ImageFormat.Png);
return captcha;
}
private string GenerateRandomCode()
{
// 生成随机验证码
string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuilder captcha = new StringBuilder();
for (int i = 0; i < 6; i++)
{
captcha.Append(characters[random.Next(characters.Length)]);
}
return captcha.ToString();
}
private void AddNoiseAndLines(Graphics graphics)
{
// 添加噪点
Random random = new Random();
for (int i = 0; i < 100; i++)
{
int x = random.Next(graphics.VisibleClipBounds.Width);
int y = random.Next(graphics.VisibleClipBounds.Height);
graphics.FillRectangle(Brushes.Black, x, y, 1, 1);
}
// 添加干扰线条
for (int i = 0; i < 10; i++)
{
int x1 = random.Next(graphics.VisibleClipBounds.Width);
int y1 = random.Next(graphics.VisibleClipBounds.Height);
int x2 = random.Next(graphics.VisibleClipBounds.Width);
int y2 = random.Next(graphics.VisibleClipBounds.Height);
graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
}
}
```
3. 创建一个名为"GenerateCaptchaImage.aspx"的新页面,用于生成验证码图片。
```csharp
protected void Page_Load(object sender, EventArgs e)
{
string captcha = Session["Captcha"] as string;
if (!string.IsNullOrEmpty(captcha))
{
Bitmap image = new Bitmap(200, 80);
Graphics graphics = Graphics.FromImage(image);
graphics.DrawString(captcha, new Font("Arial", 40), Brushes.Black, new PointF(10, 10));
AddNoiseAndLines(graphics);
Response.ContentType = "image/png";
image.Save(Response.OutputStream, ImageFormat.Png);
}
}
private void AddNoiseAndLines(Graphics graphics)
{
// 添加噪点和干扰线条的代码同上
}
```
4. 在登录页面中添加一个TextBox控件用于输入验证码,并设置其ID为"txtCaptcha",以及一个Button控件用于提交表单,并设置其ID为"btnSubmit"。
5. 在后台代码中校验验证码。
```csharp
protected void btnSubmit_Click(object sender, EventArgs e)
{
string captcha = Session["Captcha"] as string;
string inputCaptcha = txtCaptcha.Text.Trim();
if (!string.IsNullOrEmpty(captcha) && !string.IsNullOrEmpty(inputCaptcha))
{
if (captcha.Equals(inputCaptcha, StringComparison.OrdinalIgnoreCase))
{
// 验证码输入正确
// 执行登录逻辑
}
else
{
// 验证码输入错误
// 提示用户重新输入验证码
}
}
}
```