Asp. The development of no flush verification code in net (complete code)

Source: Internet
Author: User
Tags add array end flush net string tostring trim
Copy CodeThe code is as follows:
<%@ Page language= "C #" autoeventwireup= "true" codefile= "Login.aspx.cs" inherits= "Login"%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title> Untitled Page </title>
<script type= "Text/javascript" >
function Dofresh () {
document.getElementById ("Image1"). src = "verifycode.aspx";
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<table>
<tr>
<td>
Verification code: <asp:textbox id= "Txtvalidatecode" runat= "Server" ></asp:TextBox>
</td>
<td>
<asp:image id= "Image1" runat= "Server"/>
<a href= "Javascript:dofresh ();" > Can't see clearly?</a>
</td>
</tr>
<tr>
&LT;TD align= "center" colspan= "2" >
<br/>
<asp:literal id= "literrormsg" runat= "Server" ></asp:Literal>
<asp:button id= "btnsubmit" runat= "Server" text= "OK"/>
</td>
</tr>
</table>
</div>
</form>
</body>


Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;

public partial class Login:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
if (! Page.IsPostBack)
{
Image1.imageurl = "verifycode.aspx";
}
}
protected void btnSubmit_Click (object sender, EventArgs e)
{
if (session["Validatecode"]!= null)
{
String outputvalidatecode = session["Validatecode"] as String;
String inputvalidatecode = TxtValidateCode.Text.Trim ();
if (String.Compare (Outputvalidatecode, Inputvalidatecode, True)!= 0)
{
Response.Write (' <script>javascript:alert (' Input validation code Error! ');</script> ");
Literrormsg.text = "The authentication code entered is wrong!" ";
}
Else
{
Response.Write (' <script>javascript:alert (' Input verification code is correct! ');</script> ");
Literrormsg.text = "The authentication code entered is correct!" ";
}
}
}
#region call the following method to implement the client save Cookie Authentication mode
private void Validatemethod ()
{
if (request.cookies["checkcode"] = = null)
{
Literrormsg.text = "Your browser settings have been disabled cookies, you must set the browser to allow the use of cookies to use the system." ";
Literrormsg.visible = true;
Return
}
if (String.Compare (request.cookies["Checkcode"). Value, TextBox1.Text.ToString (). Trim (), True)!= 0)
{
Literrormsg.text = "<font color=red> Sorry, verification code error!" </font> ";
Literrormsg.visible = true;
Return
}
Else
{
Literrormsg.text = "<font color=green> Congratulations, verify code input correct!" </font> ";
Literrormsg.visible = true;
}
}
#endregion
}

Verifycode.aspx for the default generated code
Copy CodeThe code is as follows:
Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Drawing;
Using System.Drawing.Imaging;
Using System.Drawing.Drawing2D;
Using System.IO;
public partial class VerifyCode:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
Generatevalidatecode ();
Generateverifyimage (4);//generateverifyimage (int length)
}

#region "No refresh imitation Google waveform distorted color" captcha style 0___generatevalidatecode ()
private void Generatevalidatecode ()
{
This. Length = This.length;
This. FontSize = this.fontsize;
This. Chaos = This.chaos;
This. BackgroundColor = This.backgroundcolor;
This. Chaoscolor = This.chaoscolor;
This. Codeserial = this.codeserial;
This. Colors = this.colors;
This. Fonts = this.fonts;
This. Padding = this.padding;
String vnum = this. Createverifycode (); Take random Code
session["Validatecode"] = Vnum.toupper ()//obtain a CAPTCHA to verify later
This. Createimageonpage (Vnum, this. context); Output picture
Cookie authentication mode, using cookies to take the value of the verification code
RESPONSE.COOKIES.ADD (New HttpCookie ("Checkcode", code. ToUpper ()));
}
#endregion
#region Verification Code Length (the length of the default 4 Authenticode)
int length = 4;
public int Length
{
get {return length;}
set {length = value;}
}
#endregion
#region Authenticode font size (default 40 pixels for distortion to appear, you can modify it yourself)
int fontsize = 22;
public int FontSize
{
get {return fontsize;}
set {fontsize = value;}
}
#endregion
#region Border Supplement (default 1 pixels)
int padding = 2;
public int Padding
{
get {return padding;}
set {padding = value;}
}
#endregion
#region whether to output dryness point (default does not output)
BOOL Chaos = true;
public bool Chaos
{
get {return chaos;}
set {chaos = value;}
}
#endregion
#region the color of the output dryness point (default gray)
Color chaoscolor = Color.lightgray;
Public Color Chaoscolor
{
get {return chaoscolor;}
set {Chaoscolor = value;}
}
#endregion
#region Custom background color (default white)
Color backgroundcolor = Color.White;
Public Color BackgroundColor
{
get {return backgroundcolor;}
set {backgroundcolor = value;}
}
#endregion
#region Custom Random Color array
color[] Colors = {color.black, color.red, Color.darkblue, Color.green, Color.orange, Color.brown, Color.darkcyan, Color. Purple};
Public color[] Colors
{
get {return colors;}
set {colors = value;}
}
#endregion
#region a custom font array
string[] fonts = {"Arial", "Georgia"};
Public string[] Fonts
{
get {return fonts;}
set {fonts = value;}
}
#endregion
#region custom Random code string sequence (separated by commas)
String codeserial = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j, K,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z ";
public string codeserial
{
get {return codeserial;}
set {codeserial = value;}
}
#endregion
#region Generate waveform Filter effect
Private Const Double PI = 3.1415926535897932384626433832795;
Private Const Double PI2 = 6.283185307179586476925286766559;
<summary>
Sine Wave distorted picture
</summary>
<param name= "srcbmp" > Picture path </param>
<param name= "Bxdir" > If skew is selected as true</param>
<param name= "Nmultvalue" > Waveform amplitude multiples, the greater the degree of distortion of the higher, generally 3</param>
<param name= "Dphase" > Waveform starting phase, value interval [0-2*pi) </param>
<returns></returns>
Public Bitmap twistimage (Bitmap srcbmp, bool Bxdir, double dmultvalue, double dphase)
{
Bitmap destbmp = new Bitmap (srcbmp.width, srcbmp.height);
Fill a bitmap background with white
System.Drawing.Graphics graph = graphics.fromimage (destbmp);
Graph. FillRectangle (New SolidBrush (Color.White), 0, 0, destbmp.width, destbmp.height);
Graph. Dispose ();
Double Dbaseaxislen = Bxdir? (double) Destbmp.height: (double) destbmp.width;
for (int i = 0; i < destbmp.width; i++)
{
for (int j = 0; J < Destbmp.height; J + +)
{
Double dx = 0;
DX = Bxdir? (PI2 * (double) j)/Dbaseaxislen: (PI2 * (double) i)/Dbaseaxislen;
DX + + dphase;
Double dy = math.sin (dx);
Get the color of the current point
int noldx = 0, Noldy = 0;
NOLDX = Bxdir? i + (int) (DY * dmultvalue): i;
Noldy = Bxdir? J:j + (int) (DY * dmultvalue);
System.Drawing.Color Color = Srcbmp.getpixel (i, j);
if (noldx >= 0 && noldx < destbmp.width
&& noldy >= 0 && noldy < destbmp.height)
{
Destbmp.setpixel (NOLDX, noldy, color);
}
}
}
return destbmp;
}
#endregion
#region Generate check code picture
Public Bitmap Createimagecode (string code)
{
int fsize = fontsize;
int fwidth = fsize + Padding;
int imagewidth = (int) (code. Length * fwidth) + 4 + Padding * 2;
int imageheight = fsize * 2 + Padding;
System.Drawing.Bitmap image = New System.Drawing.Bitmap (imagewidth, imageheight);
Graphics g = graphics.fromimage (image);
G.clear (BackgroundColor);
Random rand = new Random ();
Add a randomly generated dryness point to the background
if (this. Chaos)
{
Pen pen = new Pen (chaoscolor, 0);
int c = Length * 10;
for (int i = 0; i < C; i++)
{
int x = rand. Next (image. Width);
int y = rand. Next (image. Height);
G.drawrectangle (pen, x, Y, 1, 1);
}
}
int left = 0, top = 0, Top1 = 1, top2 = 1;
int n1 = (imageheight-fontsize-padding * 2);
int n2 = N1/4;
Top1 = n2;
Top2 = n2 * 2;
Font F;
Brush b;
int CIndex, Findex;
Validation code characters for random fonts and colors
for (int i = 0; i < code. Length; i++)
{
CIndex = Rand. Next (colors.length-1);
Findex = Rand. Next (fonts.length-1);
f = new System.Drawing.Font (Fonts[findex], fsize, System.Drawing.FontStyle.Bold);
b = new System.Drawing.SolidBrush (Colors[cindex]);
if (i% 2 = 1)
{
top = TOP2;
}
Else
{
top = TOP1;
}
left = i * fwidth;
g.DrawString (code. Substring (i, 1), F, B, left, top);
}
Draw a border border color for Color.gainsboro
G.drawrectangle (New Pen (Color.gainsboro, 0), 0, 0, image. Width-1, image. HEIGHT-1);
G.dispose ();
Generate Waveform (ADD by 51aspx.com)
Image = Twistimage (image, True, 4, 4);
return image;
}
#endregion
#region output the created picture to the page
public void Createimageonpage (string code, HttpContext context)
{
Response.bufferoutput = true; Special attention
Response.Cache.SetExpires (DateTime.Now.AddMilliseconds (-1));//Special attention
Response.Cache.SetCacheability (Httpcacheability.nocache)/special attention
Response.appendheader ("Pragma", "No-cache"); Special attention
MemoryStream ms = new MemoryStream ();
Bitmap image = this. Createimagecode (code);
Image. Save (MS, Imageformat.jpeg);
Response.clearcontent ();
Response.ContentType = "Image/jpeg";
Response.BinaryWrite (Ms. ToArray ());
Response.End ();
Ms. Close ();
ms = NULL;
Image. Dispose ();
image = NULL;
}
#endregion
#region Generate random character codes
public string Createverifycode (int codelen)
{
if (Codelen = 0)
{
Codelen = Length;
}
string[] arr = codeserial.split (', ');
String code = "";
int randvalue =-1;
Random rand = new Random (unchecked (int) DateTime.Now.Ticks));
for (int i = 0; i < Codelen; i++)
{
Randvalue = Rand. Next (0, arr. LENGTH-1);
Code + + Arr[randvalue];
}
return code;
}
public string Createverifycode ()
{
Return Createverifycode (0);
}
#endregion
#region Another authentication code style generateverifyimage (int length)
<summary>
Output the created picture to the page
</summary>
public void generateverifyimage (int nlen)
{
String validatecode = "";//generated Verification code
int nbmpwidth = Getimagewidth (Nlen);
int nbmpheight = Getimageheight ();
System.Drawing.Bitmap bmp = New System.Drawing.Bitmap (nbmpwidth, nbmpheight);
To bend an image
Twistimage (BMP, True, 12, 2);

1. Generate Random background color
int nRed, Ngreen, Nblue; Ternary color of the background
System.Random rd = new Random ((int) System.DateTime.Now.Ticks);
nRed = Rd. Next (255)% 128 + 128;
Ngreen = Rd. Next (255)% 128 + 128;
nblue = Rd. Next (255)% 128 + 128;
2. Fill a bitmap background
System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage (BMP);
Graph. FillRectangle (New SolidBrush (System.Drawing.Color.FromArgb (nRed, Ngreen, Nblue))
, 0
, 0
, Nbmpwidth
, nbmpheight);

3. Draw a disturbing line with a slightly darker color than the background
int nlines = 3;
System.Drawing.Pen Pen = new System.Drawing.Pen (System.Drawing.Color.FromArgb (NRED-17, NGREEN-17, NBLUE-17), 2);
for (int a = 0; a < nlines; a++)
{
int x1 = Rd. Next ()% Nbmpwidth;
int y1 = Rd. Next ()% Nbmpheight;
int x2 = Rd. Next ()% Nbmpwidth;
int y2 = Rd. Next ()% Nbmpheight;
Graph. DrawLine (pen, x1, y1, x2, y2);
}
The character set that you use can be expanded immediately, and you can control the probability of the character appearing
String strcode = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
4. Loop to get the character and draw
for (int i = 0; i < Nlen; i++)
{
int x = (i * + Rd. Next (3));
int y = Rd. Next (4) + 1;
Determine font
System.Drawing.Font font = new System.Drawing.Font ("Courier new",//Text font type
+ Rd. Next ()% 4,//text font size
System.Drawing.FontStyle.Bold);//text font style
char C = strcode[rd. Next (Strcode.length)]; Random Fetch character
Validatecode + + c.tostring ();
Drawing characters
Graph. DrawString (c.tostring (),
Font
New SolidBrush (System.Drawing.Color.FromArgb (nRed-60 + y * 3, nGreen-60 + y * 3, nBlue-40 + y * 3)),
X
y);
}
session["Validatecode"] = Validatecode;
To bend an image
Twistimage (BMP, True, 4, 4);
Response.bufferoutput = true; Special attention
Response.Cache.SetExpires (DateTime.Now.AddMilliseconds (-1));//Special attention
Response.Cache.SetCacheability (Httpcacheability.nocache)/special attention
Response.appendheader ("Pragma", "No-cache"); Special attention
5. Output byte stream
MemoryStream bstream = new MemoryStream ();
Bmp. Save (Bstream, imageformat.jpeg);
Response.clearcontent ();
Response.ContentType = "Image/jpeg";
Response.BinaryWrite (Bstream. ToArray ());
Response.End ();
Bstream. Close ();
Bstream = null;
Bmp. Dispose ();
BMP = NULL;
Graph. Dispose ();
}
<summary>
Get the width of the verification code picture
</summary>
<paramname= "Validatenumlength" > Verification Code length </param>
<returns></returns>
public static int getimagewidth (int validatenumlength)
{
return (int) (validatenumlength + 5);
}
<summary>
Get the height of the verification code
</summary>
<returns></returns>
public static int Getimageheight ()
{
return 25;
}
#endregion
}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.