添加一个web窗体
然后将下面的代码添加进去
并重命名该窗体为checkCode
aspx;
public class ValidateCode : SystemWebUIPage
{
private void Page_Load(object sender SystemEventArgs e)
{
thisCreateCheckCodeImage(GenerateCheckCode())
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASPNET Web 窗体设计器所必需的
//
InitializeComponent()
baseOnInit(e)
}
/// <summary>
/// 设计器支持所需的方法 不要使用代码编辑器修改
/// 此方法的内容
/// </summary>
private void InitializeComponent()
{
thisLoad += new SystemEventHandler(thisPage_Load)
}
#endregion
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = StringEmpty;
SystemRandom random = new Random()
for(int i=; i<; i++)
{
number = randomNext()
if(number % == )
code = (char)( + (char)(number % ))
else
code = (char)(A + (char)(number % ))
checkCode += codeToString()
}
ResponseCookiesAdd(new HttpCookie(CheckCode checkCode))
return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{
if(checkCode == null || checkCodeTrim() == StringEmpty)
return;
SystemDrawingBitmap image = new SystemDrawingBitmap((int)MathCeiling((checkCodeLength * )) )
Graphics g = GraphicsFromImage(image)
try
{
//生成随机生成器
Random random = new Random()
//清空图片背景色
gClear(ColorWhite)
//画图片的背景噪音线
for(int i=; i<; i++)
{
int x = randomNext(imageWidth)
int x = randomNext(imageWidth)
int y = randomNext(imageHeight)
int y = randomNext(imageHeight)
gDrawLine(new Pen(ColorSilver) x y x y)
}
Font font = new SystemDrawingFont(Arial (SystemDrawingFontStyleBold | SystemDrawingFontStyleItalic))
SystemDrawingDrawingDLinearGradientBrush brush = new SystemDrawingDrawingDLinearGradientBrush(new Rectangle( imageWidth imageHeight) ColorBlue ColorDarkRed f true)
gDrawString(checkCode font brush )
//画图片的前景噪音点
for(int i=; i<; i++)
{
int x = randomNext(imageWidth)
int y = randomNext(imageHeight)
imageSetPixel(x y ColorFromArgb(randomNext()))
}
//画图片的边框线
gDrawRectangle(new Pen(ColorSilver) imageWidth imageHeight )
SystemIOMemoryStream ms = new SystemIOMemoryStream()
imageSave(ms SystemDrawingImagingImageFormatGif)
ResponseClearContent()
ResponseContentType = image/Gif;
ResponseBinaryWrite(msToArray())
}
finally
{
gDispose()
imageDispose()
}
}
}
在你要显示验证码的窗体中添加一个image控件并命名为imgCheckCode用于显示验证码再添加一个lable并命名为lblMessage用于显示错误信息然后在该窗体的Page_Load中添加thisimgCheckCode ImageUrl =checkCodeaspx;
在登录页面的登录按钮的处理事件中使用以下代码判断验证码
private void btnLogin_Click(object sender SystemWebUIImageClickEventArgs e)
{
if(RequestCookies[checkCode] == null)
{
lblMessageText = 您的浏览器设置已被禁用 Cookies您必须设置浏览器允许使用 Cookies 选项后才能使用本系统;
lblMessageVisible = true;
return;
}
if(StringCompare(RequestCookies[checkCode]Value txtCheckCodeText true) != )
{
lblMessageText = 验证码错误请输入正确的验证码;
lblMessageVisible = true;
return;
}
}
这样就能实现你所要的验证码验证了