[VB] 使用圖形驗證碼範例

使用圖形驗證碼(VB)

前言


網路上常常看到發文或登入時需要輸入圖型驗證碼,使用圖型驗證碼可以防止惡意攻擊,

接下來我們看看怎麼實做。

 

使用方法


首先建立一支aspx檔案,命名為 ValidateCode.aspx

HTML頁不用動到,直接切換到後置程式碼中貼上以下代碼

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Drawing

Partial Public Class ValidateCode
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        '清除該頁輸出緩存,設置該頁無緩存  
        Response.Buffer = True
        Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0)
        Response.Expires = 0
        Response.CacheControl = "no-cache"
        Response.AppendHeader("Pragma", "No-Cache")

        ' 5位數字的驗證碼    
        Dim str_ValidateCode As String = GetRandomNumberString(5)
        ' 用於驗證的Session        
        Session("ValidateCode") = str_ValidateCode
        Me.CreateCheckCodeImage(str_ValidateCode)
    End Sub

    ' 隨機生成數字字符串    
    Public Function GetRandomNumberString(ByVal int_NumberLength As Integer) As String
        Dim str_Number As String = String.Empty
        Dim theRandomNumber As New Random()
        For int_index As Integer = 0 To int_NumberLength - 1
            str_Number += theRandomNumber.[Next](10).ToString()
        Next
        Return str_Number
    End Function

    '產生驗證圖
    Private Sub CreateCheckCodeImage(ByVal checkCode As String)
        If checkCode Is Nothing OrElse checkCode.Trim() = [String].Empty Then
            Return
        End If
        '設圖片定長寬
        Dim image As New System.Drawing.Bitmap(CInt(Math.Ceiling((checkCode.Length * 13.5))), 22)
        Dim g As System.Drawing.Graphics = Graphics.FromImage(image)
        Try
            '生成隨機生成器          
            Dim random As New Random()
            '清空圖片背景色       
            g.Clear(Color.White)
            For i As Integer = 0 To 24
                '畫圖片的背景噪音線          
                Dim x1 As Integer = random.[Next](image.Width)
                Dim x2 As Integer = random.[Next](image.Width)
                Dim y1 As Integer = random.[Next](image.Height)
                Dim y2 As Integer = random.[Next](image.Height)
                g.DrawLine(New Pen(Color.Silver), x1, y1, x2, y2)
            Next
            Dim font As Font = New System.Drawing.Font("Arial", 10, (System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Italic))
            Dim brush As New System.Drawing.Drawing2D.LinearGradientBrush(New Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, True)
            g.DrawString(checkCode, font, brush, 10, 2)
            For i As Integer = 0 To 99
                '畫圖片的前景噪音點     
                Dim x As Integer = random.[Next](image.Width)
                Dim y As Integer = random.[Next](image.Height)
                image.SetPixel(x, y, Color.FromArgb(random.[Next]()))
            Next
            '畫圖片的邊框線         
            g.DrawRectangle(New Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1)
            Dim ms As 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()
        End Try
    End Sub
End Class

 

再來覆寫Image控制項,讓它可以在工具箱中出現。

建立一個新的Class,命名為 TBValidateCode

貼上以下程式碼:

Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ComponentModel

Namespace WebControls
    < _
    Description("圖形驗證碼控制項"), _
    ToolboxData("<{0}:TBValidateCode runat=server>") _
    > _
    Public Class TBValidateCode
        Inherits System.Web.UI.WebControls.Image

        Dim FValidateCodeUrl As String

        ''' 
        ''' 圖形驗證碼產生頁面網址。
        ''' 
        < _
        Description("圖形驗證碼產生頁面網址"), _
        DefaultValue("") _
        > _
        Public Property ValidateCodeUrl() As String
            Get
                Return FValidateCodeUrl
            End Get
            Set(ByVal value As String)
                FValidateCodeUrl = value
            End Set
        End Property

        '覆寫Render方法
        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            Dim sUrl As String
            Dim sScript As String

            sUrl = Me.ValidateCodeUrl
            If String.IsNullOrEmpty(sUrl) Then
                sUrl = "~/formobj/ValidateCode.aspx"
            End If
            If Me.BorderWidth = Unit.Empty Then
                Me.BorderWidth = Unit.Pixel(1)
            End If
            If Me.AlternateText = String.Empty Then
                Me.AlternateText = "圖形驗證碼"
            End If
            Me.ToolTip = "滑鼠點二下可重新產生驗證碼"
            Me.ImageUrl = sUrl
            Me.ImageAlign = Web.UI.WebControls.ImageAlign.Middle
            Me.Height = 20
            Me.Width = 60
            If Not Me.DesignMode Then
                sScript = String.Format("this.src='{0}?flag='+Math.random();", Me.Page.ResolveClientUrl(sUrl))
                Me.Attributes("ondblclick") = sScript
            End If
            Me.Style(HtmlTextWriterStyle.Cursor) = "pointer"

            MyBase.Render(writer)
        End Sub

        ''' 
        ''' 檢查輸入驗證碼是否正確。
         ''' 
        ''' 輸入驗證碼。 
         ''' 驗證成功傳回 True,反之傳回 False。
        Public Function ValidateCode(ByVal Code As String) As Boolean
            If Me.Page.Session("ValidateCode") Is Nothing Then Return False
            If Me.Page.Session("ValidateCode") = Code Then
                Return True
            Else
                Return False
            End If
        End Function
    End Class
End Namespace

 

產生出來的驗證碼會存在Session("ValidateCode") 這個Session中,

之後在要使用的頁面中呼叫TBValidateCode的ValidateCode方法來比對使用者輸入的文字框數值是否一樣即可。

例如:

 

Public Class CheckCode
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    End Sub
    Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
            If TBValidateCode1.ValidateCode(txtCode.Text.Trim) = True Then
                Label1.Text = "驗證碼正確"
            Else
                Label1.Text = "驗證碼錯誤"
            End If
    End Sub
End Class

 

 

 


以上文章敘述如有錯誤及觀念不正確,請不吝嗇指教
如有侵權內容也請您與我反應~謝謝您 :)