大 家对于验证码都很熟悉了,几乎每天都会和它打交道,如注册、登录,论坛回帖等。可以说验证码与我们广大网民的生活工作息息相关。当我们在输入验证码时有人 可能会觉得麻烦,虽然验证码让我们有一点小小的麻烦,但是它给我们带来了很大的好处。它可以防止利用恶意程序批量注册、发帖、灌水还能有效的防止黑客暴力 破解密码。验证码虽然一般只有简单的几个字符,但是它的作用着实不小啊!下面我们就一起看看如何实现网站中的验证码。
下面我们就来看看它们是如何产生的:
用一般处理程序生成验证码
using
System;
using
System.Web;
using
System.Drawing;
using
System.Drawing.Drawing2D;
using
System.Web.SessionState;
namespace
Web.handler
{
/// <summary>
/// WaterMark 的摘要说明
/// </summary>
public
class
WaterMark : IHttpHandler, IRequiresSessionState
// 要使用session必须实现该接口,记得要导入System.Web.SessionState命名空间
{
public
void
ProcessRequest(HttpContext context)
{
string
checkCode = GenCode(5);
// 产生5位随机字符
context.Session[
"Code"
] = checkCode;
//将字符串保存到Session中,以便需要时进行验证
System.Drawing.Bitmap image =
new
System.Drawing.Bitmap(70, 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random =
new
Random();
//清空图片背景色
g.Clear(Color.White);
// 画图片的背景噪音线
int
i;
for
(i = 0; i < 25; 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);
}
Font font =
new
System.Drawing.Font(
"Arial"
, 12, (System.Drawing.FontStyle.Bold));
System.Drawing.Drawing2D.LinearGradientBrush brush =
new
System.Drawing.Drawing2D.LinearGradientBrush(
new
Rectangle(0, 0,
image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F,
true
);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的前景噪音点
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);
context.Response.ClearContent();
context.Response.ContentType =
"image/Gif"
;
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
/// <summary>
/// 产生随机字符串
/// </summary>
/// <param name="num">随机出几个字符</param>
/// <returns>随机出的字符串</returns>
private
string
GenCode(
int
num)
{
//验证码中出现的字符
string
str =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
;
//str中的值就是将来会在验证码中出现的字符
char
[] chastr = str.ToCharArray();
string
code =
""
;
Random rd =
new
Random();
int
i;
for
(i = 0; i < num; i++)
{
//code += source[rd.Next(0, source.Length)];
code += str.Substring(rd.Next(0, str.Length), 1);
}
return
code;
}
public
bool
IsReusable
{
get
{
return
false
;
}
}
}
}
|
刷新验证码的HTML及Javascript代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="nwessystem.Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
head
runat
=
"server"
>
<
title
>登录窗体</
title
>
<
link
href
=
"../css/login.css"
rel
=
"stylesheet"
type
=
"text/css"
/>
<
script
language
=
"javascript"
type
=
"text/javascript"
>
//刷新验证码的js函数
function changeCode() {
var imgNode = document.getElementById("vimg");
//重新加载验证码,达到刷新的目的
imgNode.src = "../handler/WaterMark.ashx?t=" + (new Date()).valueOf(); // 这里加个时间的参数是为了防止浏览器缓存的问题
}
</
script
>
</
head
>
<
body
>
<
p
>验证码:<
img
src
=
"../handler/WaterMark.ashx"
id
=
"vimg"
alt
=
"点击刷新验证码"
onclick
=
"changeCode() "
/><
asp:TextBox
ID
=
"txtCode"
runat
=
"server"
CssClass
=
"txtcode"
></
asp:TextBox
></
p
>
</
body
>
</
html
>
|
登录时判断验证码是否正确
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
BLL;
namespace
nwessystem
{
public
partial
class
Login : System.Web.UI.Page
{
protected
void
btnLogin_Click(
object
sender, EventArgs e)
{
//检验验证码部分
string
code = txtCode.Text.Trim().ToUpper();
string
rightCode = Session[
"Code"
].ToString();
//判断验证码是否正确
if
(code != rightCode)
{
//验证码输入错误!
Page.ClientScript.RegisterStartupScript(Page.GetType(),
"message"
,
"<script language='javascript' defer>alert('验证码错误!');</script>"
);
return
;
}
//检验用户名和密码部分
string
name=txtName.Text.Trim();
string
pwd=txtPassword.Text.Trim();
bool
b = LoginManager.Login(name, pwd);
if
(b)
{
//登录成功
Page.ClientScript.RegisterStartupScript(Page.GetType(),
"message"
,
"<script language='javascript' defer>alert('登录成功!');</script>"
);
}
else
{
//登录失败
Page.ClientScript.RegisterStartupScript(Page.GetType(),
"message"
,
"<script language='javascript' defer>alert('登录失败,用户名或密码错误!');</script>"
);
}
}
}
}
|
好了,通过上面简单的代码就可以实现验证码的生成与验证了。代码里注释很详细了,相信不用我再写多余的说明,大家也都可以看懂。如果还是不懂欢迎在下方留言。博客水平有限,希望各位多多指正!