欢迎光临
我们一直在努力

Asp.net 实现验证码功能的Web控件-.NET教程,Asp.Net开发

建站超值云服务器,限时71元/月

asp.net的设计方式和设计理念和其他的如asp,jsp,php,perl

等都不一样,几乎是完全的面向对象设计!代码的复用就是其

中差异较大的特点之一,asp.net除了可以用include以外,还提供

了比较有特点的web控件,包括:ascx形式和带设计时支持的控

件[本文属于后者],为了熟悉这些新概念,我自己写了个web控件。

在实际项目中运行使用良好,以后,要有时间,我还将不断改进。

validatecode控件的使用方法:

第一步:

编译我提供的原代码, 然后,在studio.net 2003工具栏上, 选择"添加/移除项", 选中编译好的dll文件。

第二步:

工具栏上就会多一个web控件validatecode,做好一个web窗体,在studio.net 2003开发界面上,直接把控件拖到webform上,就ok!

第三步:

在该控件的graphicok事件中获取,验证码的字符信息,用于和用户录入做比较!

最后一步:

在网站的根目录下,建一个temp目录(也可以自己指定目录),用于存放验证码

图片,不用担心,代码会自动删除无用的图片!

原代码如下:

using system;

using system.web.ui;

using system.web.ui.webcontrols;

using system.componentmodel;

using system.io;

using system.drawing;

using system.drawing.drawing2d;

using system.drawing.imaging;

namespace webvalidatecode

{

/// <summary>

/// validatecode 的摘要说明。

/// 设计者:王海波 2004-11-20

/// </summary>

///

public enum graphictype

{

jpg = 0,

gif = 1,

png = 2,

bmp = 3,

}

//[toolboxbitmap(@"d:\dotnetapp\validatecode\validatecode.bmp") ] //设置控件在工具箱上的图标

public class validatecode : system.web.ui.webcontrols.webcontrol ,inamingcontainer

{

private int pcodelen=5;

private int pchartwidth=100;

private int pchartheight=20;

private graphictype pcharttype;

private string pauthencode;

private string ptempimageurlpath="/temp";

private string pauthenimagefullname;

private string pauthenimagefullurl;

//生成校验码的变量 start

private bitmap validateimage;

private graphics g;

//生成校验码的变量 end

private textbox txt=new textbox();

private system.web.ui.webcontrols.image img= new system.web.ui.webcontrols.image();

#region 定义控件事件

public delegate void graphiccreated(object sender, eventargs e);

public event eventhandler graphicok; //在校验图片生成结束以后触发

protected virtual void ongraphicok(object sender, eventargs e)

{

if (graphicok != null)

{

//invokes the delegates.

graphicok(sender, e);

}

}

#endregion

#region 控件属性

//生成校验码的长度

[bindable(true),browsable(true),category("appearance"),defaultvalue(true),description("需要验证码的长度,建议在5~8位之间!")]

public int codelength

{

get

{

return pcodelen;

}

set

{

pcodelen = value;

}

}

//生成校验码的长度

[bindable(true),browsable(true),category("appearance"),defaultvalue(true),description("生成验证码图片的临时存放路径,要求必须是网站下的虚拟目录!")]

public string tempimageurlpath

{

get

{

return ptempimageurlpath;

}

set

{

ptempimageurlpath = value;

}

}

[bindable(true),browsable(true),category("appearance"),defaultvalue(graphictype.jpg),description("选择生成校验图文件的类型(jpg;gif;png;bmp)!")]

public graphictype charttype

{

get

{

return pcharttype;

}

set

{

pcharttype = value;

}

}

//生成校验码图片的宽度

public int chartwidth

{

get

{

return pchartwidth;

}

set

{

pchartwidth = value;

}

}

//生成校验码图片的高度

public int chartheight

{

get

{

return pchartheight;

}

set

{

pchartheight = value;

}

}

//需要生成的校验码

public string authencode

{

get

{

return pauthencode;

}

set

{

pauthencode = value;

}

}

#endregion

/// <summary>

/// 将此控件呈现给指定的输出参数。

/// </summary>

/// <param name="output"> 要写出到的 html 编写器 </param>

protected override void render(htmltextwriter output)

{

system.web.ui.webcontrols.image objimage;

//textbox objtxt;

//绘制包含的控件

objimage = (system.web.ui.webcontrols.image) controls[0];

//objtxt = (textbox) controls[1];

if(pauthencode==null)

pauthencode=getvalidatecode();

ongraphicok(this,eventargs.empty );

getrandomimage(pauthencode);

objimage.imageurl=pauthenimagefullurl;

objimage.rendercontrol(output);

}

/// <summary>

/// 给控件添加子控件

/// </summary>

protected override void createchildcontrols( )

{

//controls.add(btn);

controls.add(img);

//controls.add(txt);

}

/// <summary>

/// 控件load时候属性的初始化

/// </summary>

/// <param name="e"></param>

protected override void onload(system.eventargs e)

{

eraseoldgraphic(); //删除过期的图片

}

/// <summary>

/// 生成随机的

/// </summary>

private void makerandomfilename()

{

string strrandname=datetime.now.ticks.tostring()+".jpg";

pauthenimagefullname=this.page.mappath(tempimageurlpath)+@"\"+strrandname;

pauthenimagefullurl=tempimageurlpath+"/"+strrandname;

}

private void getrandomimage(string strvalidatecode)

{

//生成随即图片的全名,和全url

makerandomfilename();

validateimage = new bitmap(pchartwidth, pchartheight, pixelformat.format24bpprgb); // .format24bpprgb);

g = graphics.fromimage(validateimage);

g.clear(color.lightgray) ;

//g.drawstring(strvalidatecode , new font("宋体",16,fontstyle.bold),new solidbrush(color.darkred),new pointf(2,2));

for(int i=0;i<strvalidatecode.length;i++)

{

random r = new random();

pointf startpos=new pointf(r.next(3,6)+(r.next(12,14)*i ),r.next(-1,2) );

g.drawstring(strvalidatecode.substring(i,1) , new font("宋体",14,fontstyle.italic),new solidbrush(color.blue),startpos);

}

//g.fillrectangle(new lineargradientbrush(new point(0,0), new point(120,30), color.fromargb(0,0,0,0),color.fromargb(255,255,255,255)),0,0,120,30);

switch(pcharttype)

{

case graphictype.jpg:

validateimage.save(pauthenimagefullname, imageformat.jpeg);

break;

case graphictype.gif:

validateimage.save(pauthenimagefullname, imageformat.gif);

break;

case graphictype.png:

validateimage.save(pauthenimagefullname, imageformat.png);

break;

case graphictype.bmp:

validateimage.save(pauthenimagefullname, imageformat.bmp);

break;

default:

validateimage.save(pauthenimagefullname, imageformat.jpeg);

break;

}

validateimage.dispose();

g.dispose();

}

/// <summary>

/// 动态从数字和字母组成的元素中动态选择生成校验码

/// </summary>

private string getvalidatecode()

{

char[] s = new char[]{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};

string num = "";

random r = new random();

//根据用户需要的长度来定义验证码的位数

for(int i = 0; i < codelength; i++)

{

num += s[r.next(0, s.length)].tostring();

}

return num;

}

/// <summary>

/// 清除时间超过20秒的临时图片记录

/// </summary>

/// <returns>成功返回true,失败返回false</returns>

public bool eraseoldgraphic()

{

try

{

directoryinfo dinfo=new directoryinfo(this.page.mappath(ptempimageurlpath));

fileinfo[] fileset;

if(dinfo.exists)

{

switch(pcharttype)

{

case graphictype.jpg:

fileset=dinfo.getfiles("*.jpg");

break;

case graphictype.gif:

fileset=dinfo.getfiles("*.gif");

break;

case graphictype.png:

fileset=dinfo.getfiles("*.png");

break;

case graphictype.bmp:

fileset=dinfo.getfiles("*.bmp");

break;

default:

fileset=dinfo.getfiles("*.jpg");

break;

}

foreach(fileinfo fileinfo in fileset)

{

if(fileinfo.exists)

{

datetime dts=datetime.now;

datetime dtc=fileinfo.creationtime;

timespan ts=dts-dtc;

if(ts.seconds>20)

{

fileinfo.delete();

}

}

}

}

return true;

}

catch(ioexception ioe)

{

return false;

}

}

}

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Asp.net 实现验证码功能的Web控件-.NET教程,Asp.Net开发
分享到: 更多 (0)

相关推荐

  • 暂无文章