程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net 驗證碼的簡單制作(vb.net+C#)

asp.net 驗證碼的簡單制作(vb.net+C#)

編輯:ASP.NET基礎
網站上驗證碼效果一般制作方法是:
1)使用HttpHandler(一般處理程序)繪制隨機驗證碼的圖,以及產生隨機碼,並輸出到頁面的OutputStream中。
2)頁面中使用異步方式(js等)進行刷新當前頁面的驗證碼。
【示例】
1)創建一個“一般應用處理程序ashx”,代碼如下:
[C#]
復制代碼 代碼如下:
public class ValidationCode : IHttpHandler
{
//隨機發生器
static Random r = new Random(Guid.NewGuid().GetHashCode());
//排除黑色、透明色顏色,因為底色黑色
static PropertyInfo[] colors = (typeof(Brushes).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Static)).Where(p => p.Name != "Black" && p.Name != "Transparent").Select(p => p).ToArray();
//排除黑色顏色,因為底色黑色
static PropertyInfo[] linecolors = (typeof(Pens).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Static)).Where(p => p.Name != "Black").Select(p => p).ToArray();
//獲取靜態類Brushes實例對象
static object colorobj = typeof(Brushes).GetConstructor(BindingFlags.NonPublic, null, Type.EmptyTypes, null);
//獲取靜態類Pens實例對象
static object penobj = typeof(Pens).GetConstructor(BindingFlags.NonPublic, null, Type.EmptyTypes, null);
//每個隨機字符的寬度
const float PERNUMBERWIDTH = 40.0f;
//每個字符的高度
const float PERNUMBERHEIGHT = 50.0f;
public void ProcessRequest(HttpContext context)
{
//獲取要產生多少隨機數(默認產生5個)
int reqNum = 5;
if (context.Request.QueryString["reqNum"] != null)
{
int.TryParse(context.Request.QueryString["reqNum"], out reqNum);
}
//產生多少大的背景圖
Bitmap bt = new Bitmap((int)(PERNUMBERWIDTH*reqNum), (int)PERNUMBERHEIGHT);
Graphics g = Graphics.FromImage(bt);
//產生4個隨機數(number可以被保存到Session中)
string numbers = "";
//繪制數字
for (int i = 1; i <= reqNum; i++)
{
numbers += r.Next(0, 9).ToString();
var color = (PropertyInfo)colors.GetValue(r.Next(0, colors.Length));
context.Response.Write(color.Name + "<br/>");
Brush randomcolor = (Brush)color.GetValue(colorobj, null);
g.DrawString(numbers[i-1].ToString(), new Font("黑體", PERNUMBERWIDTH),randomcolor, new PointF((i-1)*PERNUMBERWIDTH, 0f));
}
//繪制隨機線條
int linenum = r.Next(10, 21);
for (int i = 1; i <= linenum; i++)
{
var linecolor = (PropertyInfo)linecolors.GetValue(r.Next(0, colors.Length));
Pen randomcolor = (Pen)linecolor.GetValue(penobj, null);
g.DrawLine(randomcolor, new PointF((float)(r.NextDouble() * PERNUMBERWIDTH * reqNum), (float)(r.NextDouble() * PERNUMBERHEIGHT)), new PointF((float)(r.NextDouble() * PERNUMBERWIDTH * reqNum), (float)(r.NextDouble() * PERNUMBERHEIGHT)));
}
g.Dispose();
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
bt.Save(context.Response.OutputStream, ImageFormat.Jpeg);
bt.Dispose();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}

[VB.NET]
復制代碼 代碼如下:
Public Class ValidationCode
Implements IHttpHandler
'隨機發生器
Shared r As New Random(Guid.NewGuid().GetHashCode())
'排除黑色、透明色顏色,因為底色黑色
Shared colors As PropertyInfo() = (GetType(Brushes).GetProperties(System.Reflection.BindingFlags.[Public] Or System.Reflection.BindingFlags.GetProperty Or System.Reflection.BindingFlags.[Static])).Where(Function(p) p.Name <> "Black" AndAlso p.Name <> "Transparent").[Select](Function(p) p).ToArray()
'排除黑色顏色,因為底色黑色
Shared linecolors As PropertyInfo() = (GetType(Pens).GetProperties(System.Reflection.BindingFlags.[Public] Or System.Reflection.BindingFlags.GetProperty Or System.Reflection.BindingFlags.[Static])).Where(Function(p) p.Name <> "Black").[Select](Function(p) p).ToArray()
'獲取靜態類Brushes實例對象
Shared colorobj As Object = GetType(Brushes).GetConstructor(BindingFlags.NonPublic, Nothing, Type.EmptyTypes, Nothing)
'獲取靜態類Pens實例對象
Shared penobj As Object = GetType(Pens).GetConstructor(BindingFlags.NonPublic, Nothing, Type.EmptyTypes, Nothing)
'每個隨機字符的寬度
Const PERNUMBERWIDTH As Single = 40F
'每個字符的高度
Const PERNUMBERHEIGHT As Single = 50F
Public Sub ProcessRequest(context As HttpContext)
'獲取要產生多少隨機數(默認產生5個)
Dim reqNum As Integer = 5
If context.Request.QueryString("reqNum") IsNot Nothing Then
Integer.TryParse(context.Request.QueryString("reqNum"), reqNum)
End If
'產生多少大的背景圖
Dim bt As New Bitmap(CInt(Math.Truncate(PERNUMBERWIDTH * reqNum)), CInt(Math.Truncate(PERNUMBERHEIGHT)))
Dim g As Graphics = Graphics.FromImage(bt)
'產生4個隨機數(number可以被保存到Session中)
Dim numbers As String = ""
'繪制數字
For i As Integer = 1 To reqNum
numbers += r.[Next](0, 9).ToString()
Dim color = DirectCast(colors.GetValue(r.[Next](0, colors.Length)), PropertyInfo)
context.Response.Write(Convert.ToString(color.Name) & "<br/>")
Dim randomcolor As Brush = DirectCast(color.GetValue(colorobj, Nothing), Brush)
g.DrawString(numbers(i - 1).ToString(), New Font("黑體", PERNUMBERWIDTH), randomcolor, New PointF((i - 1) * PERNUMBERWIDTH, 0F))
Next
'繪制隨機線條
Dim linenum As Integer = r.[Next](10, 21)
For i As Integer = 1 To linenum
Dim linecolor = DirectCast(linecolors.GetValue(r.[Next](0, colors.Length)), PropertyInfo)
Dim randomcolor As Pen = DirectCast(linecolor.GetValue(penobj, Nothing), Pen)
g.DrawLine(randomcolor, New PointF(CSng(r.NextDouble() * PERNUMBERWIDTH * reqNum), CSng(r.NextDouble() * PERNUMBERHEIGHT)), New PointF(CSng(r.NextDouble() * PERNUMBERWIDTH * reqNum), CSng(r.NextDouble() * PERNUMBERHEIGHT)))
Next
g.Dispose()
context.Response.Clear()
context.Response.ContentType = "image/jpeg"
bt.Save(context.Response.OutputStream, ImageFormat.Jpeg)
bt.Dispose()
context.Response.[End]()
End Sub
Public ReadOnly Property IsReusable() As Boolean
Get
Return False
End Get
End Property
End Class

注意:
1)一些諸如Brushes等特定因為是公用的,需要通過反射獲取全部的顏色屬性列表,因此使用了靜態變量,這樣不必每次都初始化,節省內存和時間。
2)Brushes避免黑色和透明色(本示例背景色是黑色),Pens只需避免黑色即可。有關Brushes顏色,可以查閱:http://msdn.microsoft.com/zh-cn/library/system.windows.media.brush(v=vs.95).aspx
3)Bitmap類是用於繪制使用的,一般是空白的黑色背景。一般配合Image類+Graphics畫布使用,進行繪制。
4)BitMap的Save方法有若干個重載版本,其中之一可以指定輸出流以及設置圖片格式。本示例就是使用了這個函數。
【應用】

Html中代碼(驗證碼部分,局部):
復制代碼 代碼如下:
<h1>
驗證碼
</h1>
<script>
function ChangeSD() {
document.getElementById("imgSD").src = "";
document.getElementById("imgSD").src = "/ValidationCode.ashx?reqNum=10";
};
</script>
<img src="/ValidationCode.ashx?reqNum=10" id="imgSD" />
<input type="button" value="Change Validation Key" onclick="ChangeSD()" />

注意,之所以使用js設置img的src兩次,是因為重復的路徑不會引發請求。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved