asp.net弄一个验证码源代码
时间: 2023-11-28 13:05:17 浏览: 82
以下是ASP.NET的验证码源代码:
ASPX页面:
```html
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Captcha.aspx.cs" Inherits="Captcha" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="imgCaptcha" runat="server" />
<br />
<asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>
<asp:Button ID="btnCheck" runat="server" Text="Check" OnClick="btnCheck_Click" />
</div>
</form>
</body>
</html>
```
ASPX.CS页面:
```csharp
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web.UI;
public partial class Captcha : Page
{
private string GenerateRandomCode(int length)
{
const string chars = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789";
var random = new Random();
var result = new char[length];
for (var i = 0; i < length; i++)
{
result[i] = chars[random.Next(chars.Length)];
}
return new string(result);
}
protected void Page_Load(object sender, EventArgs e)
{
var randomCode = GenerateRandomCode(6);
Session["Captcha"] = randomCode;
using (var bitmap = new Bitmap(100, 30))
{
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(Color.White);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawString(randomCode, new Font("Arial", 16), Brushes.Black, new Point(10, 0));
Response.ContentType = "image/png";
bitmap.Save(Response.OutputStream, ImageFormat.Png);
}
}
}
protected void btnCheck_Click(object sender, EventArgs e)
{
if (txtCaptcha.Text.Equals(Session["Captcha"]))
{
Response.Write("Correct!");
}
else
{
Response.Write("Incorrect!");
}
}
}
```
这个代码生成一个6位随机验证码,并将其存储在会话中。然后使用Graphics类在ASP.NET页面上绘制验证码图像,并将其发送回客户端。用户输入他们看到的验证码并单击“检查”按钮, ASP.NET代码将会检查用户输入是否与会话中存储的验证码匹配。
阅读全文