A general method for verifying code effects on a Web site is:
1 Use HttpHandler (general handler) to draw the graph of random verification code, and generate random code, and output to the outputstream of the page.
2 The page uses the asynchronous method (JS, etc.) to refresh the current page of the verification code.
Example
1 Create a "general application handler ashx" with the following code:
[C #]
Copy Code code as follows:
public class Validationcode:ihttphandler
{
Random generator
static Random R = new Random (Guid.NewGuid (). GetHashCode ());
Exclude black, transparent color because of black background
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 ();
Exclude black color because of black background
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 ();
Get static class Brushes instance Object
Static Object colorobj = typeof (Brushes). GetConstructor (BindingFlags.NonPublic, NULL, type.emptytypes, NULL);
Get static Class Pens instance Object
Static Object penobj = typeof (Pens). GetConstructor (BindingFlags.NonPublic, NULL, type.emptytypes, NULL);
Width of each random character
const float pernumberwidth = 40.0f;
The height of each character
const float pernumberheight = 50.0f;
public void ProcessRequest (HttpContext context)
{
Gets how many random numbers to generate (5 by default)
int reqnum = 5;
if (context. request.querystring["Reqnum"]!= null)
{
Int. TryParse (context. request.querystring["Reqnum"], out reqnum);
}
How many large background figures are produced
Bitmap BT = new Bitmap (int) (pernumberwidth*reqnum), (int) pernumberheight);
Graphics g = Graphics.fromimage (BT);
Generates 4 random numbers (number can be saved to session)
String numbers = "";
Draw a number
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 ("bold", Pernumberwidth), Randomcolor, New PointF ((i-1) *pernumberwidth, 0f));
}
Draw a random line
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]
Copy Code code as follows:
Public Class Validationcode
Implements IHttpHandler
' Random generators '
Shared R as New Random (Guid.NewGuid (). GetHashCode ())
' Exclude black, transparent color because of black background
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 ()
' Exclude black colors, because the background color is black
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 ()
' Get static class brushes instance Object
Shared colorobj as Object = GetType (brushes). GetConstructor (BindingFlags.NonPublic, nothing, type.emptytypes, nothing)
' Get static Class pens instance Object
Shared penobj as Object = GetType (Pens). GetConstructor (BindingFlags.NonPublic, nothing, type.emptytypes, nothing)
' width of each random character
Const pernumberwidth as Single = 40F
' The height of each character
Const pernumberheight as Single = 50F
Public Sub ProcessRequest (context as HttpContext)
' Get how many random numbers to generate (5 by default)
Dim Reqnum as Integer = 5
If context. Request.QueryString ("Reqnum") IsNot nothing Then
Integer.tryparse (context. Request.QueryString ("Reqnum"), Reqnum)
End If
' How many large background figures are produced
Dim BT as New Bitmap (CInt (math.truncate (Pernumberwidth * reqnum)), CInt (math.truncate))
Dim g as Graphics = Graphics.fromimage (BT)
' Generates 4 random numbers (number can be saved to session)
Dim numbers as String = ""
' Draw a number
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 ("bold", Pernumberwidth), Randomcolor, New PointF ((i-1) * pernumberwidth, 0F))
Next
' Draw a random line
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
Attention:
1 Some specific, such as brushes, because they are public, need to get all the list of color attributes through reflection, so use static variables so that you don't have to initialize each time, saving memory and time.
2 brushes avoid black and transparent colors (This example background color is black), pens only need to avoid black. For brushes colors, you can refer to: Http://msdn.microsoft.com/zh-cn/library/system.windows.media.brush (v=vs.95). aspx
3 The bitmap class is used for drawing and is generally a blank black background. Generally with the image class +graphics canvas used, to draw.
4 the Save method for bitmap has several overloaded versions, one of which can specify the output stream and format the picture. This is the example that uses this function.
Application
Code in HTML (part of verification Code, partial):
Copy Code code as follows:
Verification Code
<script>
function Changesd () {
document.getElementById ("Imgsd"). src = "";
document.getElementById ("Imgsd"). src = "/validationcode.ashx?reqnum=10";
};
</script>
<input type= "button" value= "Change Validation Key" onclick= "changesd ()"/>
Note that the reason for using JS to set the IMG src two times is because the duplicate path does not raise the request.