使用session进行asp.net验证码验证

时间:2013-09-14 13:08:55

标签: c# asp.net validation captcha

我已经在asp.net中实现了CAPTCHA并且在验证之前它运行良好,但是当我要验证它时,程序忽略任何输入文本并且表现为“不正确”,你能告诉我什么是错的吗?它或我能做什么? 这是代码:

public partial class WebForm1 : System.Web.UI.Page
{
    //string strResult;
    protected string Captcha()
    {
        string alphabt = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789";
        Random rand = new Random();

        int num1 = rand.Next(1, 36);
        int num2 = rand.Next(1, 36);
        int num3 = rand.Next(1, 36);
        int num4 = rand.Next(1, 36);
        int num5 = rand.Next(1, 36);
        int num6 = rand.Next(1, 36);

        string subStr1 = alphabt.Substring(num1, 1);
        string subStr2 = alphabt.Substring(num2, 1);
        string subStr3 = alphabt.Substring(num3, 1);
        string subStr4 = alphabt.Substring(num4, 1);
        string subStr5 = alphabt.Substring(num5, 1);
        string subStr6 = alphabt.Substring(num6, 1);

        string result = subStr1 + subStr2 + subStr3 + subStr4 + subStr5 + subStr6;
        Session["res"] = result;

        Bitmap bmpImage = new Bitmap(Server.MapPath("~/Image/bg1.jpg"));
        Graphics objGraphic = Graphics.FromImage(bmpImage);
        objGraphic.DrawString(result, new Font("arial", 12, FontStyle.Strikeout), SystemBrushes.WindowText, new PointF());
        string time = DateTime.Now.Ticks.ToString();//due to browser image cashing      
                                                    //bmpImage.Save(Server.MapPath("~/Image/securityImage.jpg"));
                                                    //return "~/Image/securityImage.jpg";
        bmpImage.Save(Server.MapPath("~/Image/securityImage" + time + ".jpg"));

        return "~/Image/securityImage" + time + ".jpg";
    }

    protected bool CaptchaValidate()
    {
        if (Session["res"].ToString() == TextBox1.Text)
            return true;
        return false;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Image1.ImageUrl = Captcha();
    }

    protected void btn1_Click(object sender, EventArgs e) //using ajax to refresh the picture
    {
        Image1.ImageUrl = Captcha();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        if (CaptchaValidate() == false)
            Label1.Text = "Incorrect ";
        else
            Label1.Text = "correct";
    }
}

提前感谢...

1 个答案:

答案 0 :(得分:0)

我刚刚重启了我的机器,就是这样! 再见,上面的代码是正确的。