http://blog.163.com/xu_shuhao/blog/static/5257748720101022697309/
Website to add a verification code, mainly to prevent the robot program bulk registration, or specific users of the registration of a specific program of violence to crack the way to continue to login, irrigation and other harmful site operations. Verification code is widely used in registration, login, messages and other information submitted to the server-side processing of the page.
It is easy to apply the CAPTCHA in ASP, there are a lot of solutions on the web. Recently in an OA project, because of the ASP. NET MVC framework used in the system, the verification code is also required on the login page, so the verification code originally used in the ASP is migrated to ASP.
The class file that the original ASP. NET site uses to generate the CAPTCHA ValidateCode.cs:
Using System;
Using System.Drawing;
Using System.Drawing.Imaging;
Using System.Web.UI;
Using System.Drawing.Drawing2D;
Using System.IO;
Namespace Senioa.mvc
{
<summary>
The class that generated the verification code
</summary>
public class Validatecode
{
Public Validatecode ()
{
}
<summary>
Maximum length of verification code
</summary>
public int MaxLength
{
get {return 10;}
}
<summary>
Minimum length of verification code
</summary>
public int MinLength
{
get {return 1;}
}
<summary>
Generate Verification Code
</summary>
<param name= "Length" > Specified verification code lengths </param>
<returns></returns>
public string Createvalidatecode (int length)
{
int[] randmembers = new Int[length];
int[] validatenums = new Int[length];
String validatenumberstr = "";
Generate a starting Sequence value
int seekseek = unchecked ((int) DateTime.Now.Ticks);
Random Seekrand = new Random (Seekseek);
int beginseek = (int) seekrand.next (0, Int32.maxvalue-length * 10000);
Int[] seeks = new Int[length];
for (int i = 0; i < length; i++)
{
Beginseek + = 10000;
Seeks[i] = Beginseek;
}
Generate random numbers
for (int i = 0; i < length; i++)
{
Random rand = new random (seeks[i]);
int pownum = 1 * (int) Math.pow (ten, length);
Randmembers[i] = rand. Next (Pownum, Int32.MaxValue);
}
Extracting random numbers
for (int i = 0; i < length; i++)
{
String numstr = Randmembers[i]. ToString ();
int numlength = Numstr.length;
Random rand = new Random ();
int numposition = rand. Next (0, numLength-1);
Validatenums[i] = Int32.Parse (numstr.substring (numposition, 1));
}
Generate Verification Code
for (int i = 0; i < length; i++)
{
Validatenumberstr + = Validatenums[i]. ToString ();
}
return validatenumberstr;
}
<summary>
Create a picture of the verification code
</summary>
<param name= "Containspage" > Page object to export to </param>
<param name= "Validatenum" > Verification Code </param>
public void Createvalidategraphic (string validatecode)
{
Bitmap image = new Bitmap ((int) math.ceiling (validatecode.length * 12.0), 22);
Graphics g = graphics.fromimage (image);
Try
{
Generate Random Generators
Random random = new random ();
Clear the background color of the picture
G.clear (Color.White);
Interference lines for drawing pictures
for (int i = 0; i <; i++)
{
int x1 = Random. Next (image. Width);
int x2 = random. Next (image. Width);
int y1 = random. Next (image. Height);
int y2 = random. Next (image. Height);
G.drawline (New Pen (color.silver), x1, y1, x2, y2);
}
Font font = new Font ("Arial", page, (FontStyle.Bold | Fontstyle.italic));
LinearGradientBrush brush = new LinearGradientBrush (new Rectangle (0, 0, image. Width, image. Height),
Color.Blue, color.darkred, 1.2f, true);
g.DrawString (Validatecode, Font, Brush, 3, 2);
Foreground interference point of picture painting
for (int i = 0; i <; i++)
{
int x = random. Next (image. Width);
int y = random. Next (image. Height);
Image. SetPixel (x, Y, Color.FromArgb (random. Next ()));
}
Draw the border line of a picture
G.drawrectangle (New Pen (Color.silver), 0, 0, image. Width-1, image. HEIGHT-1);
Save picture data
MemoryStream stream = new MemoryStream ();
Image. Save (stream, imageformat.jpeg);
Output picture Stream
ContainsPage.Response.Clear ();
ContainsPage.Response.ContentType = "Image/jpeg";
ContainsPage.Response.BinaryWrite (stream. ToArray ());
}
Finally
{
G.dispose ();
Image. Dispose ();
}
}
<summary>
Get the length of the Verification code picture
</summary>
<param name= "Validatenumlength" > Length of verification code </param>
<returns></returns>
public static int getimagewidth (int validatenumlength)
{
return (int) (VALIDATENUMLENGTH * 12.0);
}
<summary>
Get the height of the verification code
</summary>
<returns></returns>
public static double Getimageheight ()
{
return 22.5;
}
}
}
To fit the ASP. NET. MVC framework, the method of modifying its output picture stream is createvalidategraphic:
<summary>
Create a picture of the verification code
</summary>
<param name= "Containspage" > Page object to export to </param>
<param name= "Validatenum" > Verification Code </param>
Public byte[] Createvalidategraphic (string validatecode)
{
Bitmap image = new Bitmap ((int) math.ceiling (validatecode.length * 12.0), 22);
Graphics g = graphics.fromimage (image);
Try
{
Generate Random Generators
Random random = new random ();
Clear the background color of the picture
G.clear (Color.White);
Interference lines for drawing pictures
for (int i = 0; i <; i++)
{
int x1 = Random. Next (image. Width);
int x2 = random. Next (image. Width);
int y1 = random. Next (image. Height);
int y2 = random. Next (image. Height);
G.drawline (New Pen (color.silver), x1, y1, x2, y2);
}
Font font = new Font ("Arial", page, (FontStyle.Bold | Fontstyle.italic));
LinearGradientBrush brush = new LinearGradientBrush (new Rectangle (0, 0, image. Width, image. Height),
Color.Blue, color.darkred, 1.2f, true);
g.DrawString (Validatecode, Font, Brush, 3, 2);
Foreground interference point of picture painting
for (int i = 0; i <; i++)
{
int x = random. Next (image. Width);
int y = random. Next (image. Height);
Image. SetPixel (x, Y, Color.FromArgb (random. Next ()));
}
Draw the border line of a picture
G.drawrectangle (New Pen (Color.silver), 0, 0, image. Width-1, image. HEIGHT-1);
Save picture data
MemoryStream stream = new MemoryStream ();
Image. Save (stream, imageformat.jpeg);
Output picture Stream
return stream. ToArray ();
}
Finally
{
G.dispose ();
Image. Dispose ();
}
}
In Controller.cs, add an action to set the generated verification code to the session and output the CAPTCHA image:
Public ActionResult Getvalidatecode ()
{
Validatecode Vcode = new Validatecode ();
String code = Vcode.createvalidatecode (5);
session["Validatecode"] = code;
byte[] bytes = vcode.createvalidategraphic (code);
Return File (bytes, @ "Image/jpeg");
}
To be called: in the page that needs to use the verification code, add the tag:
Effects such as:
To account/login this action, simply add the validation code to the session:
[Acceptverbs (Httpverbs.post)]
Public ActionResult Login (string userName, string password, bool rememberme, string returnurl,string code)
{
if (session["Validatecode"]. ToString ()! = code)
{
Modelstate.addmodelerror ("Code", "Validate code is error");
return View ();
}
Verify user name, Password here
if (! Validatelogon (userName, password))
{
return View ();
}
Validation successful
Formsauthentication.setauthcookie (UserName, rememberme);
if (! String.IsNullOrEmpty (RETURNURL))
{
Return Redirect (RETURNURL);
}
Else
{
Return redirecttoaction ("Index", "Home");
}
}
To implement the login page, click on the picture switch verification code, you can add this JS code in the login page to implement the Refresh verification code:
<script type= "Text/javascript" src= "Http://www.cnblogs.com/Scripts/jquery-1.3.2-vsdoc.js" ></script>
<script type= "Text/javascript" >
$ (function () {
$ ("#valiCode"). Bind ("click", Function () {
THIS.SRC = ". /account/getvalidatecode?time= "+ (new Date ()). GetTime ();
});
Alert ("good");
});
</script>
At this point, the CAPTCHA feature has been implemented successfully in ASP.
ASP. NET Verification Code (C #) MVC