asp.net中3种验证码示例(实现代码)(数字,数字字母混和,汉字)
程序员文章站
2024-03-05 15:52:07
效果如图所示:default.aspx 复制代码 代码如下:
&nbs...
效果如图所示:
default.aspx
复制代码 代码如下:
<table> <tr> <td class="style1"> (验证码测试)</td> <td> <asp:label id="label1" runat="server"></asp:label> <asp:image id="image1" runat="server" height="22px" imageurl="~/validnums.aspx" width="58px" /> <asp:image id="image2" runat="server" height="22px" imageurl="~/getvalid.aspx" width="58px" /></td> </tr> <tr> <td class="style1"> </td> <td> <asp:button id="button1" runat="server" text="登录" onclick="btnok_click" /> <asp:button id="button2" runat="server" text="取消" /> </td> </tr> </table>
复制代码 代码如下:
using system; using system.collections.generic; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; public partial class _default : system.web.ui.page { protected void page_load(object sender, eventargs e) { if (!page.ispostback) { string getnums = getvali(); label1.text = getnums; } } /// <summary> /// 随机生成4位数 /// </summary> /// <returns>返回生成的随机数</returns> public string getvali() { string strsvali = "0,1,2,3,4,5,6,7,8,9"; string[] valiarray = strsvali.split(','); string returnnum = ""; int nums = -1; random vrand = new random(); for (int n = 1; n < 5; n++) { if (nums != -1) { vrand = new random(n * nums * unchecked((int)datetime.now.ticks)); } int t = vrand.next(10); nums = t; returnnum += valiarray[t]; } session["valid"] = returnnum; return returnnum; } protected void btnok_click(object sender, eventargs e) { if (session["valid"].tostring() == textbox3.text) { clientscript.registerstartupscript(this.gettype(),"ss","<script>alert('您已经成功通过登录验证!')</script>"); } else { clientscript.registerstartupscript(this.gettype(), "ss", "<script>alert('您输入的验证码错误!')</script>"); } } } getvalid.aspx (可以直接将该页面作为源赋值给imageurl) 前台为空,后台代码如下:
复制代码 代码如下:
using system; using system.collections; using system.configuration; using system.data; using system.linq; using system.web; using system.web.security; using system.web.ui; using system.web.ui.htmlcontrols; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.xml.linq; using system.text; using system.drawing; public partial class getvalid : system.web.ui.page { protected void page_load(object sender, eventargs e) { if (!ispostback) { string validatenum = getvalids(); //成生4位随机字符串 createimage(validatenum); //将生成的随机字符串绘成图片 session["validnums"] = validatenum; //保存验证码 } } public static string getvalids() { //获取gb2312编码页(表) encoding gb = encoding.getencoding("gb2312"); //调用函数产生4个随机中文汉字编码 object[] bytes = createregioncode(4); //根据汉字编码的字节数组解码出中文汉字 string s = string.empty; foreach (object byt in bytes) { string str1 = gb.getstring((byte[])convert.changetype(byt, typeof(byte[]))); s = s + str1; } //输出的控制台 return s; } public static object[] createregioncode(int strlength) { //定义一个字符串数组储存汉字编码的组成元素 string[] rbase = new string[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; random rnd = new random(); //定义一个object数组用来 object[] bytes = new object[strlength]; /*每循环一次产生一个含两个元素的十六进制字节数组,并将其放入bject数组中 每个汉字有四个区位码组成 区位码第1位和区位码第2位作为字节数组第一个元素 区位码第3位和区位码第4位作为字节数组第二个元素 */ for (int i = 0; i < strlength; i++) { //区位码第1位 int r1 = rnd.next(11, 14); string str_r1 = rbase[r1].trim(); //区位码第2位 rnd = new random(r1 * unchecked((int)datetime.now.ticks) + i); //更换随机数发生器的种子避免产生重复值 int r2; if (r1 == 13) { r2 = rnd.next(0, 8); } else { r2 = rnd.next(0, 16); } string str_r2 = rbase[r2].trim(); //区位码第3位 rnd = new random(r2 * unchecked((int)datetime.now.ticks) + i); int r3 = rnd.next(10, 16); string str_r3 = rbase[r3].trim(); //区位码第4位 rnd = new random(r3 * unchecked((int)datetime.now.ticks) + i); int r4; if (r3 == 10) { r4 = rnd.next(1, 16); } else if (r3 == 15) { r4 = rnd.next(0, 15); } else { r4 = rnd.next(0, 16); } string str_r4 = rbase[r4].trim(); //定义两个字节变量存储产生的随机汉字区位码 byte byte1 = convert.tobyte(str_r1 + str_r2, 16); byte byte2 = convert.tobyte(str_r3 + str_r4, 16); //将两个字节变量存储在字节数组中 byte[] str_r = new byte[] { byte1, byte2 }; //将产生的一个汉字的字节数组放入object数组中 bytes.setvalue(str_r, i); } return bytes; } //生成图片 private void createimage(string validatenum) { if (validatenum == null || validatenum.trim() == string.empty) return; //生成bitmap图像 system.drawing.bitmap image = new system.drawing.bitmap(validatenum.length * 12 + 10, 22); graphics g = graphics.fromimage(image); try { //生成随机生成器 random random = new random(); //清空图片背景色 g.clear(color.white); //画图片的背景噪音线 for (int 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.coral), x1, y1, x2, y2); } font font = new system.drawing.font("arial", 8); 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(validatenum, font, brush, 2, 2); //画图片的前景噪音点 for (int i = 0; i < 100; i++) { int x = random.next(image.width); int y = random.next(image.height); image.setpixel(x, y, color.fromargb(random.next())); } //画图片的边框线 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); response.clearcontent(); response.contenttype = "image/gif"; response.binarywrite(ms.toarray()); } finally { g.dispose(); image.dispose(); } } } validnums.aspx (可以直接将该页面作为源赋值给imageurl) 前台为空,后台代码如下:
复制代码 代码如下:
using system; using system.collections; using system.configuration; using system.data; using system.linq; using system.web; using system.web.security; using system.web.ui; using system.web.ui.htmlcontrols; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.xml.linq; using system.drawing; public partial class validnums : system.web.ui.page { protected void page_load(object sender, eventargs e) { if (!ispostback) { string validatenum = createrandomnum(4); //成生4位随机字符串 createimage(validatenum); //将生成的随机字符串绘成图片 session["validnums"] = validatenum; //保存验证码 } } //生成随机字符串 private string createrandomnum(int numcount) { string allchar = "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,w,x,y,z"; string[] allchararray = allchar.split(',');//拆分成数组 string randomnum = ""; int temp = -1;//记录上次随机数的数值,尽量避免产生几个相同的随机数 random rand = new random(); for (int i = 0; i < numcount; i++) { if (temp != -1) { rand = new random(i * temp * ((int)datetime.now.ticks)); } int t = rand.next(35); if (temp == t) { return createrandomnum(numcount); } temp = t; randomnum += allchararray[t]; } return randomnum; } //生成图片 private void createimage(string validatenum) { if (validatenum == null || validatenum.trim() == string.empty) return; //生成bitmap图像 system.drawing.bitmap image = new system.drawing.bitmap(validatenum.length * 12 + 10, 22); graphics g = graphics.fromimage(image); try { //生成随机生成器 random random = new random(); //清空图片背景色 g.clear(color.white); //画图片的背景噪音线 for (int 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.coral), x1, y1, x2, y2); } font font = new system.drawing.font("arial", 12, (system.drawing.fontstyle.bold | system.drawing.fontstyle.italic)); 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(validatenum, font, brush, 2, 2); //画图片的前景噪音点 for (int i = 0; i < 100; i++) { int x = random.next(image.width); int y = random.next(image.height); image.setpixel(x, y, color.fromargb(random.next())); } //画图片的边框线 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); response.clearcontent(); response.contenttype = "image/gif"; response.binarywrite(ms.toarray()); } finally { g.dispose(); image.dispose(); } } } 以上是3种验证码的全部代码。 另外也可以使用ashx请求验证码的方式,本示例仅使用session存值处理。 |