ASP.NET中的无刷新验证码的开发(完整代码)
程序员文章站
2024-03-07 13:52:57
复制代码 代码如下: <%@ page language="c#" autoeventwireup="true" codefile="login.aspx.cs" i...
复制代码 代码如下:
<%@ page language="c#" autoeventwireup="true" codefile="login.aspx.cs" inherits="login" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="head1" runat="server">
<title>无标题页</title>
<script type="text/javascript">
function dofresh() {
document.getelementbyid("image1").src = "verifycode.aspx";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
验证码:<asp:textbox id="txtvalidatecode" runat="server"></asp:textbox>
</td>
<td>
<asp:image id="image1" runat="server" />
<a href="javascript:dofresh();">看不清?</a>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<br />
<asp:literal id="literrormsg" runat="server"></asp:literal>
<asp:button id="btnsubmit" runat="server" text="确定" onclick="btnsubmit_click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
public partial class login : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
if (!page.ispostback)
{
image1.imageurl = "verifycode.aspx";
}
}
protected void btnsubmit_click(object sender, eventargs e)
{
if (session["validatecode"] != null)
{
string outputvalidatecode = session["validatecode"] as string;
string inputvalidatecode = txtvalidatecode.text.trim();
if (string.compare(outputvalidatecode, inputvalidatecode, true) != 0)
{
//response.write("<script>javascript:alert('输入的验证码错误!');</script>");
literrormsg.text = "输入的验证码错误!";
}
else
{
//response.write("<script>javascript:alert('输入的验证码正确!');</script>");
literrormsg.text = "输入的验证码正确!";
}
}
}
#region 调用下面的方法实现客户端保存cookie验证模式
private void validatemethod()
{
if (request.cookies["checkcode"] == null)
{
literrormsg.text = "您的浏览器设置已被禁用 cookies,您必须设置浏览器允许使用 cookies 选项后才能使用本系统。";
literrormsg.visible = true;
return;
}
if (string.compare(request.cookies["checkcode"].value, textbox1.text.tostring().trim(), true) != 0)
{
literrormsg.text = "<font color=red>对不起,验证码错误!</font>";
literrormsg.visible = true;
return;
}
else
{
literrormsg.text = "<font color=green>恭喜,验证码输入正确!</font>";
literrormsg.visible = true;
}
}
#endregion
}
//verifycode.aspx为默认生成的代码
复制代码 代码如下:
using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.drawing;
using system.drawing.imaging;
using system.drawing.drawing2d;
using system.io;
public partial class verifycode : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
//generatevalidatecode();
generateverifyimage(4);//generateverifyimage(int length)
}
#region 【无刷新仿google波形扭曲彩色】验证码样式0___generatevalidatecode()
private void generatevalidatecode()
{
this.length = this.length;
this.fontsize = this.fontsize;
this.chaos = this.chaos;
this.backgroundcolor = this.backgroundcolor;
this.chaoscolor = this.chaoscolor;
this.codeserial = this.codeserial;
this.colors = this.colors;
this.fonts = this.fonts;
this.padding = this.padding;
string vnum = this.createverifycode(); //取随机码
session["validatecode"] = vnum.toupper();//取得验证码,以便后来验证
this.createimageonpage(vnum, this.context); // 输出图片
//cookie验证模式, 使用cookies取验证码的值
//response.cookies.add(new httpcookie("checkcode", code.toupper()));
}
#endregion
#region 验证码长度(默认4个验证码的长度)
int length = 4;
public int length
{
get { return length; }
set { length = value; }
}
#endregion
#region 验证码字体大小(为了显示扭曲效果,默认40像素,可以自行修改)
int fontsize = 22;
public int fontsize
{
get { return fontsize; }
set { fontsize = value; }
}
#endregion
#region 边框补(默认1像素)
int padding = 2;
public int padding
{
get { return padding; }
set { padding = value; }
}
#endregion
#region 是否输出燥点(默认不输出)
bool chaos = true;
public bool chaos
{
get { return chaos; }
set { chaos = value; }
}
#endregion
#region 输出燥点的颜色(默认灰色)
color chaoscolor = color.lightgray;
public color chaoscolor
{
get { return chaoscolor; }
set { chaoscolor = value; }
}
#endregion
#region 自定义背景色(默认白色)
color backgroundcolor = color.white;
public color backgroundcolor
{
get { return backgroundcolor; }
set { backgroundcolor = value; }
}
#endregion
#region 自定义随机颜色数组
color[] colors = { color.black, color.red, color.darkblue, color.green, color.orange, color.brown, color.darkcyan, color.purple };
public color[] colors
{
get { return colors; }
set { colors = value; }
}
#endregion
#region 自定义字体数组
string[] fonts = { "arial", "georgia" };
public string[] fonts
{
get { return fonts; }
set { fonts = value; }
}
#endregion
#region 自定义随机码字符串序列(使用逗号分隔)
string codeserial = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
public string codeserial
{
get { return codeserial; }
set { codeserial = value; }
}
#endregion
#region 产生波形滤镜效果
private const double pi = 3.1415926535897932384626433832795;
private const double pi2 = 6.283185307179586476925286766559;
/// <summary>
/// 正弦曲线wave扭曲图片
/// </summary>
/// <param name="srcbmp">图片路径</param>
/// <param name="bxdir">如果扭曲则选择为true</param>
/// <param name="nmultvalue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
/// <param name="dphase">波形的起始相位,取值区间[0-2*pi)</param>
/// <returns></returns>
public bitmap twistimage(bitmap srcbmp, bool bxdir, double dmultvalue, double dphase)
{
bitmap destbmp = new bitmap(srcbmp.width, srcbmp.height);
// 将位图背景填充为白色
system.drawing.graphics graph = graphics.fromimage(destbmp);
graph.fillrectangle(new solidbrush(color.white), 0, 0, destbmp.width, destbmp.height);
graph.dispose();
double dbaseaxislen = bxdir ? (double)destbmp.height : (double)destbmp.width;
for (int i = 0; i < destbmp.width; i++)
{
for (int j = 0; j < destbmp.height; j++)
{
double dx = 0;
dx = bxdir ? (pi2 * (double)j) / dbaseaxislen : (pi2 * (double)i) / dbaseaxislen;
dx += dphase;
double dy = math.sin(dx);
// 取得当前点的颜色
int noldx = 0, noldy = 0;
noldx = bxdir ? i + (int)(dy * dmultvalue) : i;
noldy = bxdir ? j : j + (int)(dy * dmultvalue);
system.drawing.color color = srcbmp.getpixel(i, j);
if (noldx >= 0 && noldx < destbmp.width
&& noldy >= 0 && noldy < destbmp.height)
{
destbmp.setpixel(noldx, noldy, color);
}
}
}
return destbmp;
}
#endregion
#region 生成校验码图片
public bitmap createimagecode(string code)
{
int fsize = fontsize;
int fwidth = fsize + padding;
int imagewidth = (int)(code.length * fwidth) + 4 + padding * 2;
int imageheight = fsize * 2 + padding;
system.drawing.bitmap image = new system.drawing.bitmap(imagewidth, imageheight);
graphics g = graphics.fromimage(image);
g.clear(backgroundcolor);
random rand = new random();
//给背景添加随机生成的燥点
if (this.chaos)
{
pen pen = new pen(chaoscolor, 0);
int c = length * 10;
for (int i = 0; i < c; i++)
{
int x = rand.next(image.width);
int y = rand.next(image.height);
g.drawrectangle(pen, x, y, 1, 1);
}
}
int left = 0, top = 0, top1 = 1, top2 = 1;
int n1 = (imageheight - fontsize - padding * 2);
int n2 = n1 / 4;
top1 = n2;
top2 = n2 * 2;
font f;
brush b;
int cindex, findex;
//随机字体和颜色的验证码字符
for (int i = 0; i < code.length; i++)
{
cindex = rand.next(colors.length - 1);
findex = rand.next(fonts.length - 1);
f = new system.drawing.font(fonts[findex], fsize, system.drawing.fontstyle.bold);
b = new system.drawing.solidbrush(colors[cindex]);
if (i % 2 == 1)
{
top = top2;
}
else
{
top = top1;
}
left = i * fwidth;
g.drawstring(code.substring(i, 1), f, b, left, top);
}
//画一个边框 边框颜色为color.gainsboro
g.drawrectangle(new pen(color.gainsboro, 0), 0, 0, image.width - 1, image.height - 1);
g.dispose();
//产生波形(add by 51aspx.com)
image = twistimage(image, true, 4, 4);
return image;
}
#endregion
#region 将创建好的图片输出到页面
public void createimageonpage(string code, httpcontext context)
{
response.bufferoutput = true; //特别注意
response.cache.setexpires(datetime.now.addmilliseconds(-1));//特别注意
response.cache.setcacheability(httpcacheability.nocache);//特别注意
response.appendheader("pragma", "no-cache"); //特别注意
memorystream ms = new memorystream();
bitmap image = this.createimagecode(code);
image.save(ms, imageformat.jpeg);
response.clearcontent();
response.contenttype = "image/jpeg";
response.binarywrite(ms.toarray());
response.end();
ms.close();
ms = null;
image.dispose();
image = null;
}
#endregion
#region 生成随机字符码
public string createverifycode(int codelen)
{
if (codelen == 0)
{
codelen = length;
}
string[] arr = codeserial.split(',');
string code = "";
int randvalue = -1;
random rand = new random(unchecked((int)datetime.now.ticks));
for (int i = 0; i < codelen; i++)
{
randvalue = rand.next(0, arr.length - 1);
code += arr[randvalue];
}
return code;
}
public string createverifycode()
{
return createverifycode(0);
}
#endregion
#region 另一种验证码样式 generateverifyimage(int length)
/// <summary>
/// 将创建好的图片输出到页面
/// </summary>
public void generateverifyimage(int nlen)
{
string validatecode = "";//生成的验证码
int nbmpwidth = getimagewidth(nlen);
int nbmpheight = getimageheight();
system.drawing.bitmap bmp = new system.drawing.bitmap(nbmpwidth, nbmpheight);
//对图像进行弯曲
twistimage(bmp, true, 12, 2);
// 1. 生成随机背景颜色
int nred, ngreen, nblue; // 背景的三元色
system.random rd = new random((int)system.datetime.now.ticks);
nred = rd.next(255) % 128 + 128;
ngreen = rd.next(255) % 128 + 128;
nblue = rd.next(255) % 128 + 128;
// 2. 填充位图背景
system.drawing.graphics graph = system.drawing.graphics.fromimage(bmp);
graph.fillrectangle(new solidbrush(system.drawing.color.fromargb(nred, ngreen, nblue))
, 0
, 0
, nbmpwidth
, nbmpheight);
// 3. 绘制干扰线条,采用比背景略深一些的颜色
int nlines = 3;
system.drawing.pen pen = new system.drawing.pen(system.drawing.color.fromargb(nred - 17, ngreen - 17, nblue - 17), 2);
for (int a = 0; a < nlines; a++)
{
int x1 = rd.next() % nbmpwidth;
int y1 = rd.next() % nbmpheight;
int x2 = rd.next() % nbmpwidth;
int y2 = rd.next() % nbmpheight;
graph.drawline(pen, x1, y1, x2, y2);
}
// 采用的字符集,可以随即拓展,并可以控制字符出现的几率
string strcode = "0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
// 4. 循环取得字符,并绘制
for (int i = 0; i < nlen; i++)
{
int x = (i * 13 + rd.next(3));
int y = rd.next(4) + 1;
// 确定字体
system.drawing.font font = new system.drawing.font("courier new",//文字字体类型
12 + rd.next() % 4,//文字字体大小
system.drawing.fontstyle.bold);//文字字体样式
char c = strcode[rd.next(strcode.length)]; // 随机获取字符
validatecode += c.tostring();
// 绘制字符
graph.drawstring(c.tostring(),
font,
new solidbrush(system.drawing.color.fromargb(nred - 60 + y * 3, ngreen - 60 + y * 3, nblue - 40 + y * 3)),
x,
y);
}
session["validatecode"] = validatecode;
//对图像进行弯曲
twistimage(bmp, true, 4, 4);
response.bufferoutput = true; //特别注意
response.cache.setexpires(datetime.now.addmilliseconds(-1));//特别注意
response.cache.setcacheability(httpcacheability.nocache);//特别注意
response.appendheader("pragma", "no-cache"); //特别注意
// 5. 输出字节流
memorystream bstream = new memorystream();
bmp.save(bstream, imageformat.jpeg);
response.clearcontent();
response.contenttype = "image/jpeg";
response.binarywrite(bstream.toarray());
response.end();
bstream.close();
bstream = null;
bmp.dispose();
bmp = null;
graph.dispose();
}
///<summary>
///得到验证码图片的宽度
///</summary>
///<paramname="validatenumlength">验证码的长度</param>
///<returns></returns>
public static int getimagewidth(int validatenumlength)
{
return (int)(13 * validatenumlength + 5);
}
///<summary>
///得到验证码的高度
///</summary>
///<returns></returns>
public static int getimageheight()
{
return 25;
}
#endregion
}
下一篇: 分享AjaxPro或者Ajax实现机制