vb.net实现验证码功能

前端之家收集整理的这篇文章主要介绍了vb.net实现验证码功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

实现过程,在需要调用页面使用image控件调用验证码生成页面,验证码生成页面生成验证图片且将验证信息保存至Session中,调用页面中通过Session判断用户是否输入正确。道理是这样,以下看代码:    生成验证码页面:  gif.aspx  <%@ import namespace="System"%>  <%@ import namespace="System.io"%>  <%@ import namespace="System.Drawing"%>  <%@ import namespace="System.Drawing.Imaging"%>    <script language="vb" runat="server">  Sub Page_Load(ByVal Sender As Object,ByVal e As EventArgs)  'RndNum为生成随机码的函数,  Dim VNum As String = RndNum(4) '该值为生成验证码的位数  Session("VNum") = VNum '读取Session  ValidateCode(VNum) '根据Session生成图片  End Sub    '--------------------------------------------  '生成图象验证码函数  Sub ValidateCode(ByVal VNum)  Dim Img As System.Drawing.Bitmap  Dim g As Graphics  Dim ms As MemoryStream  Dim gheight As Integer = Int(Len(VNum) * 14)  'gheight为图片宽度,根据字符长度自动更改图片宽度  Img = New Bitmap(gheight,24)  g = Graphics.FromImage(Img)  g.DrawString(VNum,(New Font("Arial",12)),(New SolidBrush(Color.Red)),3,3) '在矩形内绘制字串(字串,字体,画笔颜色,左上x.左上y)  ms = New MemoryStream()  Img.Save(ms,ImageFormat.Png)  Response.ClearContent() '需要输出图象信息 要修改HTTP头  Response.ContentType = "image/Png"  Response.BinaryWrite(ms.ToArray())  g.Dispose()  Img.Dispose()  Response.End()  End Sub    '--------------------------------------------  '函数名称:RndNum  '函数参数:VcodeNum--设定返回随机字符串的位数  '函数功能:产生数字和字符混合的随机字符串  Function RndNum(ByVal VcodeNum)  Dim Vchar As String = "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" '需要使用中文验证,可以修改这里和ValidateCode函数中的字体  Dim VcArray() As String = Split(Vchar,",") '将字符串生成数组  Dim VNum As String = ""  Dim i As Byte  For i = 1 To VcodeNum  Randomize()  VNum = VNum & VcArray(Int(35 * Rnd())) '数组一般从0开始读取,所以这里为35*Rnd  Next  Return VNum  End Function  </script>      调用页面:  demo.aspx  <script language="vb" Runat="Server">  Sub Page_Load(Sender as object,e as eventargs)  dim VNum as string=Session("VNum")  Session.Abandon()  ViewState("VNum")=VNum  End Sub  '下面的事件代码是用来测试验证码    Sub btnSubmit_click(sender as object,e as eventargs)  '判断输入的验证码与所给是否相同  If txtValidateCode.Text = CStr(ViewState("VNum")) Then  ensonShow.text = "<font color='red'>提示:验证通过</font>"  Else  ensonShow.text = "所填写的验证码与所给的不符"  End If  End Sub    </script>  <html>  <body>  <form runat="server">  <div align="center">  <table width="750">  <tr>  <td valign="middle">验证码:</td>  <!--调用验证图片生成页--->  <td valign="top"><asp:Image id="Image1" runat="server" ImageUrl="gif.aspx" /></td>  </tr>  <tr>  <td valign="top">输入验证码:</td>  <td valign="top"><asp:textBox ID="txtValidateCode" runat="server" TextMode="SingleLine" /><font color="#FF0000" size="2">*区分大小写</font></td>  </tr>  <tr>  <td colspan="2" valign="top" align="center"><asp:button ID="btnSubmit" runat="server" Text="验证" onclick="btnSubmit_click" />  <asp:label ID="ensonShow" runat="server" />  </td>  </tr>  </table>  </div>  </form>  </body>  </html>

原文链接:https://www.f2er.com/vb/262036.html

猜你在找的VB相关文章