首页 > 学院 > 开发设计 > 正文

asp.net登录时验证码的制作与验证

2019-11-14 14:31:33
字体:
来源:转载
供稿:网友

1.新建一个页面,ImageCode.aspx

2.在Page_Load中添加如下代码

string tmp = RndNum(4);
HttpCookie a = new HttpCookie("ImageV ", tmp);
Response.Cookies.Add(a);
this.ValidateCode(tmp);

3.在该页面中添加两个方法

PRivate void ValidateCode(string VNum)
{

Bitmap Img = null;

Graphics g = null;

MemoryStream ms = null;

int gheight = VNum.Length * 12;

Img = new Bitmap(gheight, 25);

g = Graphics.FromImage(Img);

//生成随机生成器

Random random = new Random();

//背景颜色
g.Clear(Color.White);

for (int i = 0; i < 100; i++)
{

int x = random.Next(Img.Width);

int y = random.Next(Img.Height);

Img.SetPixel(x, y, Color.FromArgb(random.Next()));

}


//文字字体
Font f = new Font("Arial Black ", 12);

//文字颜色
SolidBrush s = new SolidBrush(Color.Blue);

g.DrawString(VNum, f, s, 3, 3);

ms = new MemoryStream();

Img.Save(ms, ImageFormat.Jpeg);

Response.ClearContent();

Response.ContentType = "image/Jpeg ";

Response.BinaryWrite(ms.ToArray());

g.Dispose();
Img.Dispose();
Response.End();

}

private string RndNum(int VcodeNum)
{

string Vchar = "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";

string[] VcArray = Vchar.Split(new Char[] { ',' });

string VNum = " ";
int temp = -1;
Random rand = new Random();

for (int i = 1; i < VcodeNum + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));

}
int t = rand.Next(35);
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);

}
temp = t;
VNum += VcArray[t];

}

return VNum;

}

4.在需要显示验证码的页面添加一个图片控件

5.在该页的前台页面添加如下代码:

验证码:
<asp:TextBox ID="tbx_yzm" runat="server" Width="70px"></asp:TextBox>
<asp:ImageButton ID="ibtn_yzm" runat="server" />
<a href="javascript:changeCode()"style="text-decoration: underline; font-size:10px;">换一张</a>
<script type="text/Javascript">
function changeCode()
{
document.getElementById('ibtn_yzm').src = document.getElementById('ibtn_yzm').src + '?';
}
</script>

6.在该页的Page_Load事件中添加如下代码:

ibtn_yzm.ImageUrl = "ImageCode.aspx";

7.验证该验证码是否输入正确的代码:

string code = tbx_yzm.Text;
HttpCookie htco = Request.Cookies["ImageV"];
string scode = htco.Value.ToString();
if (code != scode)
{
Response.Write("<script>alert('验证码输入不正确!')</script>");
}

8.效果


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表