Heim  >  Artikel  >  Backend-Entwicklung  >  Einfache Erstellung des asp.net-Bestätigungscodes (vb.net+C#)

Einfache Erstellung des asp.net-Bestätigungscodes (vb.net+C#)

高洛峰
高洛峰Original
2017-01-13 14:40:011384Durchsuche

Die allgemeine Produktionsmethode für den Effekt des Bestätigungscodes auf der Website ist:
1) Verwenden Sie HttpHandler (allgemeiner Handler), um ein Bild des zufälligen Bestätigungscodes zu zeichnen, den Zufallscode zu generieren und ihn an den OutputStream der auszugeben Seite.
2) Verwenden Sie auf der Seite eine asynchrone Methode (js usw.), um den Bestätigungscode der aktuellen Seite zu aktualisieren.
[Beispiel]
1) Erstellen Sie einen „allgemeinen Anwendungshandler ashx“ mit dem folgenden Code:
[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 
&#39;随机发生器 
Shared r As New Random(Guid.NewGuid().GetHashCode()) 
&#39;排除黑色、透明色颜色,因为底色黑色 
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() 
&#39;排除黑色颜色,因为底色黑色 
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() 
&#39;获取静态类Brushes实例对象 
Shared colorobj As Object = GetType(Brushes).GetConstructor(BindingFlags.NonPublic, Nothing, Type.EmptyTypes, Nothing) 
&#39;获取静态类Pens实例对象 
Shared penobj As Object = GetType(Pens).GetConstructor(BindingFlags.NonPublic, Nothing, Type.EmptyTypes, Nothing) 
&#39;每个随机字符的宽度 
Const PERNUMBERWIDTH As Single = 40F 
&#39;每个字符的高度 
Const PERNUMBERHEIGHT As Single = 50F 
Public Sub ProcessRequest(context As HttpContext) 
&#39;获取要产生多少随机数(默认产生5个) 
Dim reqNum As Integer = 5 
If context.Request.QueryString("reqNum") IsNot Nothing Then 
Integer.TryParse(context.Request.QueryString("reqNum"), reqNum) 
End If 
&#39;产生多少大的背景图 
Dim bt As New Bitmap(CInt(Math.Truncate(PERNUMBERWIDTH * reqNum)), CInt(Math.Truncate(PERNUMBERHEIGHT))) 
Dim g As Graphics = Graphics.FromImage(bt) 
&#39;产生4个随机数(number可以被保存到Session中) 
Dim numbers As String = "" 
&#39;绘制数字 
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 
&#39;绘制随机线条 
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

Hinweis:
1) Einige spezifische, wie z. B. Pinsel, sind öffentlich und müssen die gesamte Farbattributliste durch Reflektion erhalten. Daher werden statische Variablen verwendet, sodass sie nicht jedes Mal initialisiert werden müssen, was Speicherplatz spart Zeit.
2) Pinsel vermeiden Schwarz und transparente Farben (die Hintergrundfarbe in diesem Beispiel ist Schwarz) und Stifte müssen nur Schwarz vermeiden. Informationen zu Pinselfarben finden Sie unter: http://msdn.microsoft.com/zh-cn/library/system.windows.media.brush(v=vs.95).aspx
3) Die Bitmap-Klasse wird zum Zeichnen verwendet. Normalerweise wird ein leerer schwarzer Hintergrund verwendet. Wird im Allgemeinen mit der Bildklasse + Grafikleinwand zum Zeichnen verwendet.
4) Die Save-Methode von BitMap verfügt über mehrere überladene Versionen, von denen eine den Ausgabestream angeben und das Bildformat festlegen kann. In diesem Beispiel wird diese Funktion verwendet.
[Anwendung]

asp.net 验证码的简单制作(vb.net+C#)

HTML-Code (Bestätigungscodeteil, teilweise):

<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()" />

Beachten Sie, dass der Grund, warum js zum Festlegen verwendet wird img src zweimal, da wiederholte Pfade keine Anfragen auslösen.

Weitere Artikel zur einfachen Erstellung des asp.net-Bestätigungscodes (vb.net+C#) finden Sie auf der chinesischen PHP-Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn