asp.net简单生成验证码的方法
程序员文章站
2023-12-21 10:53:52
本文实例讲述了asp.net简单生成验证码的方法。分享给大家供大家参考,具体如下:
1.新建一个一般处理程序
namespace webapplication1...
本文实例讲述了asp.net简单生成验证码的方法。分享给大家供大家参考,具体如下:
1.新建一个一般处理程序
namespace webapplication1 { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [webservice(namespace = "http://tempuri.org/")] [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)] public class handler1 : ihttphandler, irequiressessionstate { public void processrequest(httpcontext context) { context.response.contenttype = "image/gif"; //建立bitmap对象,绘图 bitmap basemap = new bitmap(100, 30); graphics graph = graphics.fromimage(basemap); graph.fillrectangle(new solidbrush(color.white), 0, 0, 100, 30); font font = new font(fontfamily.genericserif, 24, fontstyle.bold, graphicsunit.pixel); random r = new random(); string letters = "abcdefghijklmnpqrstuvwxyz"; string letter; stringbuilder s = new stringbuilder(); //添加随机的五个字母 for (int x = 0; x < 5; x++) { letter = letters.substring(r.next(0, letters.length - 1), 1); s.append(letter); graph.drawstring(letter, font, new solidbrush(color.black), x * 19, r.next(0, 8)); } //混淆背景 pen linepen = new pen(new solidbrush(color.black), 2); for (int x = 0; x < 6; x++) graph.drawline(linepen, new point(r.next(0, 99), r.next(0, 29)), new point(r.next(0, 99), r.next(0, 29))); //将图片保存到输出流中 basemap.save(context.response.outputstream, imageformat.gif); context.session["checkcode"] = s.tostring(); //如果没有实现irequiressessionstate,则这里会出错,也无法生成图片 context.response.end(); } public bool isreusable { get { return false; } } } }
2.前台代码
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:textbox id="txtcode" runat="server"></asp:textbox> <img id="imgcode" alt="看不清?点击换一张" src="handler1.ashx" style="cursor:pointer" onclick="this.src=this.src+'?'" /><br /> <asp:button id="button1" runat="server" onclick="button1_click" text="button" /> </div> </form> </body> </html>
希望本文所述对大家asp.net程序设计有所帮助。