---
title: "ASP.Net随机生成验证码"
author: "piperzero"
date: "2013-01-24T18:16:00Z"
tags: []
slug: "asp-net"
draft: false
lastmod: "2013-02-21T19:49:19Z"
id: 1811350
url: "https://piperzero.iteye.com/blog/1811350"
---

//首先创建一个页面ValidateCodePage:

//创建Random的实例

Random rand=new Random();

protected void Page\_Load(object sender,EventArgs e){

//调用该方法实现的事数字和字符独立的效果

//string str=getRandomValidate(4);

//调用该方法实现的事验证码中数字和字母的组合

string str=CreateRandomCode(4);

Session\["CheckCode"]=str;

GetImageValidate(str);

}

private string getRandomValidate(int len){

int num;

int temp;

string rtnStr="";

for(int i=0;i&lt;len;i++){

num=rand.Next();

//生成数字验证码

temp=num%10+'0';

//生成字符验证码

//temp=num%26+'A';

rtnStr+=Convert.ToChar(temp).ToString();

}

return rtnStr;

}

//验证码是数字和字母的组合

private string CreateRandomCode(int codeCount){

string allChar="0,1,2,3,4,5,6,7,8,9,Q,W,E,R,T,Y,U,I,O,P,A,S,D,F,G,H,J,K,L,Z,X,C,V,B,N,M";

string \[] allCharArray=allChar.Split(',');

string randomCode="";

int temp=-1;

Random rand=new Random();

for(int i=0;i&lt;codeCount;i++){

if(temp!=-1){

rand=new Random(i\*temp\*((int) DateTime.Now.Ticks));

}

int t=rand.Next(35); //总共35个数，下标从0开始

if(temp==t){

return CreateRandomCode(codeCount);

}

temp=t;

randomCode+=allCharArray\[t]；

}

return randomCode;

}

//生成图像

private void getImageValidate(string strValue){

int width=Convert.ToInt32(strValue.Length\*14);

BitMap image=new BitMap(width,21);

Graphics g=Graphics.FromImage(image);

g.Clear(Colot,White);

drawLine(g,image);

//写验证码，定义字体的样式

Font font =new Font("Arial",12,FontStyle.Bold);

Ststem.Drawing.Drawing2D.LinearGradientBrush brush=new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0,0,image.Width-1,image.Hiight-1));

//将图像添加到页面

MemoryStream ms=new MemoryStream();

image.Save(ms,System.Drawing,Imaging.ImageFormat.Gif);

//更改http头

Response.ClearContent();

Response.ContentType="image/gif";

Response.BinaryWrite(ms.ToArray());

g.dispose();

image.dispose();

Response.End();

}

private void drawPoint(BitMap image){

for(int i-0;i&lt;10;i++){

int x=rand.Next(image.Width);

int y=rand.Next(image.Height);

image.SetPixel(x,y,Color.FromArgb(rand.Next())); //描绘随机杂点

}

//杂点颜色相同

int color=rand.Next();

for(int i=0;i&lt;20;i++){

int x=rand.Next(image.Width);

int y=rand.Next(image.Height);

image.SetPixel(x,y,Color.FromArgb(colot));

}

}

//画线

private void drawLine(Graphics g,Bitmap image){

for(int i=0;i&lt;10;i++){

int x1=rand.Next(image.Width);

int y1=rand.Next(image.Height);

int x2=rand.Next(image.Width);

int y2=rand.Next(image.Height);

g.DrawLine(new Pen(Color.Silver),x1,y1,x2,y2);

}

}

//在需要使用该验证码的地方编写如下代码

&lt;img id="imgCode" src="此处是我们编写验证码的页面路径"&gt;

&lt;a&gt;&lt;href="javascript:change();"&gt;看不清，换一张&lt;/a&gt;

想要改变框中的验证码还需要些一个js方法，方法如下所示：

function change(){

var image=document.getElementById("imgCode");

image.src="../Image/Validate.aspx?"+Math.random();

}