asp.net 验证码生成和刷新及验证
程序员文章站
2024-03-09 17:22:23
验证码技术是为了防止暴力破解等而设定的。现在一般的网站注册等都提供验证码功能,特别是腾讯更是长长的一串。文中参考了别人的代码。有了就没有必要再写了。可以读一下。不过我测试时...
验证码技术是为了防止暴力破解等而设定的。现在一般的网站注册等都提供验证码功能,特别是腾讯更是长长的一串。文中参考了别人的代码。有了就没有必要再写了。可以读一下。不过我测试时发现了两次pageload的问题。注释了两句即可。同时修改了namespaces。同时提供完整的验证说明:
1 新建verifycode.aspx
cs文件代码如下:
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
using system.drawing;
using system.drawing.imaging;
using system.drawing.text;
/**///// <summary>
/// 页面验证码程序
/// 使用:在页面中加入html代码 <img src="verifycode.aspx">
/// </summary>
public partial class verifycode : system.web.ui.page
...{
static string[] fontitems = new string[] ...{ "arial",
"helvetica",
"geneva",
"sans-serif",
"verdana"
};
static brush[] brushitems = new brush[] ...{ brushes.olivedrab,
brushes.forestgreen,
brushes.darkcyan,
brushes.lightslategray,
brushes.royalblue,
brushes.slateblue,
brushes.darkviolet,
brushes.mediumvioletred,
brushes.indianred,
brushes.firebrick,
brushes.chocolate,
brushes.peru,
brushes.goldenrod
};
static string[] brushname = new string[] ...{ "olivedrab",
"forestgreen",
"darkcyan",
"lightslategray",
"royalblue",
"slateblue",
"darkviolet",
"mediumvioletred",
"indianred",
"firebrick",
"chocolate",
"peru",
"goldenrod"
};
private static color backcolor = color.white;
private static pen bordercolor = pens.darkgray;
private static int width = 52;
private static int height = 21;
private random _random;
private string _code;
private int _brushnameindex;
override protected void oninit(eventargs e)
...{
//
// codegen: this call is required by the asp.net web form designer.
//
//initializecomponent();
//base.oninit(e);
}
/**//**//**//// <summary>
/// required method for designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void initializecomponent()
...{
//this.load += new system.eventhandler(this.page_load);
}
/**//// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void page_load(object sender, system.eventargs e)
...{
if (!ispostback)
...{
//
// todo : initialize
//
this._random = new random();
this._code = getrandomcode();
//
// todo : use session["code"] save the verifycode
//
session["code"] = this._code;
//
// todo : output image
//
this.setpagenocache();
this.onpaint();
}
}
/**//**//**//// <summary>
/// 设置页面不被缓存
/// </summary>
private void setpagenocache()
...{
response.buffer = true;
response.expiresabsolute = system.datetime.now.addseconds(-1);
response.expires = 0;
response.cachecontrol = "no-cache";
response.appendheader("pragma","no-cache");
}
/**//**//**//// <summary>
/// 取得一个 4 位的随机码
/// </summary>
/// <returns></returns>
private string getrandomcode()
...{
return guid.newguid().tostring().substring(0, 4);
}
/**//**//**//// <summary>
/// 随机取一个字体
/// </summary>
/// <returns></returns>
private font getfont()
...{
int fontindex = _random.next(0, fontitems.length);
fontstyle fontstyle = getfontstyle(_random.next(0, 2));
return new font(fontitems[fontindex], 12, fontstyle);
}
/**//**//**//// <summary>
/// 取一个字体的样式
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private fontstyle getfontstyle(int index)
...{
switch (index)
...{
case 0:
return fontstyle.bold;
case 1:
return fontstyle.italic;
default:
return fontstyle.regular;
}
}
/**//**//**//// <summary>
/// 随机取一个笔刷
/// </summary>
/// <returns></returns>
private brush getbrush()
...{
int brushindex = _random.next(0, brushitems.length);
_brushnameindex = brushindex;
return brushitems[brushindex];
}
/**//**//**//// <summary>
/// 绘画事件
/// </summary>
private void onpaint()
...{
bitmap objbitmap = null;
graphics g = null;
try
...{
objbitmap = new bitmap(width, height);
g = graphics.fromimage(objbitmap);
paint_background(g);
paint_text(g);
paint_textstain(objbitmap);
paint_border(g);
objbitmap.save(response.outputstream, imageformat.gif);
response.contenttype = "image/gif";
}
catch ...{}
finally
...{
if (null != objbitmap)
objbitmap.dispose();
if (null != g)
g.dispose();
}
}
/**//**//**//// <summary>
/// 绘画背景颜色
/// </summary>
/// <param name="g"></param>
private void paint_background(graphics g)
...{
g.clear(backcolor);
}
/**//**//**//// <summary>
/// 绘画边框
/// </summary>
/// <param name="g"></param>
private void paint_border(graphics g)
...{
g.drawrectangle(bordercolor, 0, 0, width - 1, height - 1);
}
/**//**//**//// <summary>
/// 绘画文字
/// </summary>
/// <param name="g"></param>
private void paint_text(graphics g)
...{
g.drawstring(_code, getfont(), getbrush(), 3, 1);
}
/**//**//**//// <summary>
/// 绘画文字噪音点
/// </summary>
/// <param name="g"></param>
private void paint_textstain(bitmap b)
...{
for (int n=0; n<30; n++)
...{
int x = _random.next(width);
int y = _random.next(height);
b.setpixel(x, y, color.fromname(brushname[_brushnameindex]));
}
}
}
2 页面引用:
<asp:image id="getcode" src="verifycode.aspx" runat="server" />
一般需要同时提供刷新功能(看不清楚换一张),代码如下
<asp:image id="getcode" src="verifycode.aspx" runat="server" /> <a href="javascript:getimgcode()">刷新验证码</a>
如使用了母版页,则用如下代码:
<img id="getcode" alt="" src="verifycode.aspx" /> <%--<asp:image id="getcode" src="verifycode.aspx" runat="server" />--%>
<a href="javascript:getimgcode()">刷新验证码</a>
超链接对应的javascript如下:
<script language="javascript" type="text/javascript">
function getimgcode()
{
var getimagecode = document.getelementbyid("getcode");
getimagecode.src = "verifycode.aspx";
}
</script>
3 判断验证
上述代码是将验证码存贮在session中,用code来标志。读取代码session["code"].tostring();
使用中,我们只需要比较session["code"].tostring()和文本框输入的串(textboxcode.text)是否相同即可进行判断。
if(session["code"].tostring().trim().equals(textboxcode.text.trim()))
...{
response.write("success");
}
测试通过!
1 新建verifycode.aspx
cs文件代码如下:
复制代码 代码如下:
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
using system.drawing;
using system.drawing.imaging;
using system.drawing.text;
/**///// <summary>
/// 页面验证码程序
/// 使用:在页面中加入html代码 <img src="verifycode.aspx">
/// </summary>
public partial class verifycode : system.web.ui.page
...{
static string[] fontitems = new string[] ...{ "arial",
"helvetica",
"geneva",
"sans-serif",
"verdana"
};
static brush[] brushitems = new brush[] ...{ brushes.olivedrab,
brushes.forestgreen,
brushes.darkcyan,
brushes.lightslategray,
brushes.royalblue,
brushes.slateblue,
brushes.darkviolet,
brushes.mediumvioletred,
brushes.indianred,
brushes.firebrick,
brushes.chocolate,
brushes.peru,
brushes.goldenrod
};
static string[] brushname = new string[] ...{ "olivedrab",
"forestgreen",
"darkcyan",
"lightslategray",
"royalblue",
"slateblue",
"darkviolet",
"mediumvioletred",
"indianred",
"firebrick",
"chocolate",
"peru",
"goldenrod"
};
private static color backcolor = color.white;
private static pen bordercolor = pens.darkgray;
private static int width = 52;
private static int height = 21;
private random _random;
private string _code;
private int _brushnameindex;
override protected void oninit(eventargs e)
...{
//
// codegen: this call is required by the asp.net web form designer.
//
//initializecomponent();
//base.oninit(e);
}
/**//**//**//// <summary>
/// required method for designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void initializecomponent()
...{
//this.load += new system.eventhandler(this.page_load);
}
/**//// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void page_load(object sender, system.eventargs e)
...{
if (!ispostback)
...{
//
// todo : initialize
//
this._random = new random();
this._code = getrandomcode();
//
// todo : use session["code"] save the verifycode
//
session["code"] = this._code;
//
// todo : output image
//
this.setpagenocache();
this.onpaint();
}
}
/**//**//**//// <summary>
/// 设置页面不被缓存
/// </summary>
private void setpagenocache()
...{
response.buffer = true;
response.expiresabsolute = system.datetime.now.addseconds(-1);
response.expires = 0;
response.cachecontrol = "no-cache";
response.appendheader("pragma","no-cache");
}
/**//**//**//// <summary>
/// 取得一个 4 位的随机码
/// </summary>
/// <returns></returns>
private string getrandomcode()
...{
return guid.newguid().tostring().substring(0, 4);
}
/**//**//**//// <summary>
/// 随机取一个字体
/// </summary>
/// <returns></returns>
private font getfont()
...{
int fontindex = _random.next(0, fontitems.length);
fontstyle fontstyle = getfontstyle(_random.next(0, 2));
return new font(fontitems[fontindex], 12, fontstyle);
}
/**//**//**//// <summary>
/// 取一个字体的样式
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private fontstyle getfontstyle(int index)
...{
switch (index)
...{
case 0:
return fontstyle.bold;
case 1:
return fontstyle.italic;
default:
return fontstyle.regular;
}
}
/**//**//**//// <summary>
/// 随机取一个笔刷
/// </summary>
/// <returns></returns>
private brush getbrush()
...{
int brushindex = _random.next(0, brushitems.length);
_brushnameindex = brushindex;
return brushitems[brushindex];
}
/**//**//**//// <summary>
/// 绘画事件
/// </summary>
private void onpaint()
...{
bitmap objbitmap = null;
graphics g = null;
try
...{
objbitmap = new bitmap(width, height);
g = graphics.fromimage(objbitmap);
paint_background(g);
paint_text(g);
paint_textstain(objbitmap);
paint_border(g);
objbitmap.save(response.outputstream, imageformat.gif);
response.contenttype = "image/gif";
}
catch ...{}
finally
...{
if (null != objbitmap)
objbitmap.dispose();
if (null != g)
g.dispose();
}
}
/**//**//**//// <summary>
/// 绘画背景颜色
/// </summary>
/// <param name="g"></param>
private void paint_background(graphics g)
...{
g.clear(backcolor);
}
/**//**//**//// <summary>
/// 绘画边框
/// </summary>
/// <param name="g"></param>
private void paint_border(graphics g)
...{
g.drawrectangle(bordercolor, 0, 0, width - 1, height - 1);
}
/**//**//**//// <summary>
/// 绘画文字
/// </summary>
/// <param name="g"></param>
private void paint_text(graphics g)
...{
g.drawstring(_code, getfont(), getbrush(), 3, 1);
}
/**//**//**//// <summary>
/// 绘画文字噪音点
/// </summary>
/// <param name="g"></param>
private void paint_textstain(bitmap b)
...{
for (int n=0; n<30; n++)
...{
int x = _random.next(width);
int y = _random.next(height);
b.setpixel(x, y, color.fromname(brushname[_brushnameindex]));
}
}
}
2 页面引用:
<asp:image id="getcode" src="verifycode.aspx" runat="server" />
一般需要同时提供刷新功能(看不清楚换一张),代码如下
<asp:image id="getcode" src="verifycode.aspx" runat="server" /> <a href="javascript:getimgcode()">刷新验证码</a>
如使用了母版页,则用如下代码:
<img id="getcode" alt="" src="verifycode.aspx" /> <%--<asp:image id="getcode" src="verifycode.aspx" runat="server" />--%>
<a href="javascript:getimgcode()">刷新验证码</a>
超链接对应的javascript如下:
<script language="javascript" type="text/javascript">
function getimgcode()
{
var getimagecode = document.getelementbyid("getcode");
getimagecode.src = "verifycode.aspx";
}
</script>
3 判断验证
上述代码是将验证码存贮在session中,用code来标志。读取代码session["code"].tostring();
使用中,我们只需要比较session["code"].tostring()和文本框输入的串(textboxcode.text)是否相同即可进行判断。
if(session["code"].tostring().trim().equals(textboxcode.text.trim()))
...{
response.write("success");
}
测试通过!