日期:2011-01-06  浏览次数:20510 次

在网上找了一个验证码的源代码,使用后出现如下问题:不管你输入正确与否,都会提示验证码错误。后来经过在qq群里和csdn发贴咨询,得知是ie浏览器缓存问题。在经过他人的指点后改正了错误。源代码如下:

-------------------Validate.aspx------------------

<%@ Page Language="C#" %>
<%@ import namespace="System"%>
<%@ import namespace="System.IO"%>
<%@ import namespace="System.Drawing"%>
<%@ import namespace="System.Drawing.Imaging"%>
<%@ import namespace="System.Drawing.Drawing2D"%>

<script runat="server">
private Bitmap validateimage;
private Graphics g;
 public void  Page_Load(object Sender   ,EventArgs e  ){
     Response.BufferOutput = true;   //特别注意
     Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));//特别注意
     Response.Cache.SetCacheability(HttpCacheability.NoCache);//特别注意
     Response.AppendHeader("Pragma", "No-Cache"); //特别注意
    string  VNum  =MakeValidateCode( );
 Session["VNum"]=VNum;//取得验证码,以便后来验证
    ValidateCode(VNum);}
public void  ValidateCode(string VNum)
{
validateimage = new Bitmap(60, 20, PixelFormat.Format24bppRgb);
g = Graphics.FromImage(validateimage);
g.FillRectangle(new LinearGradientBrush(new Point(0,0), new Point(110,20), Color.FromArgb(240,255,255,255),Color.FromArgb(240,255,255,255)),0,0,200,200);
g.DrawString(VNum, new Font("arial",11),new SolidBrush(Color.Red),new PointF(6,0));
g.Save();
MemoryStream ms=new MemoryStream();
validateimage.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType="image/bmp";
Response.BinaryWrite(ms.ToArray());
Response.End();
}

  string MakeValidateCode()
{
char[] s = new char[]{'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 num = "";
Random r = new Random();
for(int i = 0; i < 5; i++)
{
num += s[r.Next(0, s.Length)].ToString();
}
 return num;
}
</script>

-----------------------register.aspx------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="MyRegister.Register" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>会员注册</title>
    <LINK href="stylesheet.css" _fcksavedurl=""stylesheet.css"" _fcksavedurl=""stylesheet.css"" _fcksavedurl=""stylesheet.css"" type="text/css" rel="stylesheet">
</head>
<body>
    <form id="form1" runat="server">
    <div class="middle" style="height: 1px" >
    <div >
        <asp:Label ID="UserName" runat="server" Text="用户名:" ></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <div >
        <asp:Label ID="UserPsw" runat="server" Text="密码:" ></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></div>
    <div >
        <asp:Label ID="Label2" runat="server" Text="确认密码:" ></asp:Label>
        <asp:TextBox ID="TextBox6