点滴积累【C#】---验证码,ajax提交

效果:

思路:

借用ashx文件创建四位验证,首先生成四位随机数字。然后创建画布,再将创建好的验证码存入session,然后前台进行button按钮将文本框中的值进行ajax请求到后台,和session中的验证码进行对比,成功返回true,失败返回false.

代码:

【前台】

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="verifycodeDemo.aspx.cs" Inherits="verifycodeDemo.verifycodeDemo" %>
 2
 3 <!DOCTYPE html>
 4
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 8     <title>青苹果验证码例子</title>
 9     <script src="jquery-1.3.2.min.js"></script>
10     <script type="text/javascript">
11         //切换验证码
12         function ToggleCode(obj, codeurl) {
13             $("#" + obj).attr("src", codeurl + "?time=" + Math.random());
14         }
15         //ajax提交后台验证
16         function postAjax() {
17             var VerifyCodeValue = $("#txtVerifyCode").val();
18             $.ajax({
19                 type: ‘post‘,
20                 dataType: "text",
21                 url: "verifycodeDemo.aspx",
22                 data: "action=comparison&VerifyCode=" + VerifyCodeValue,
23                 cache: false,
24                 async: false,
25                 success: function (msg) {
26                     if (msg == "false") {
27                         alert("验证失败!sorry,青苹果");
28                         ToggleCode("Verify_codeImag", "VerifyCode.ashx");
29                         $("#txtVerifyCode").val("");
30                     }
31                     else {
32                         alert("验证成功!hello,青苹果!");
33                     }
34                 }
35             });
36         }
37     </script>
38 </head>
39 <body>
40     <form id="form1" runat="server">
41         <div>
42             <input type="text" id="txtVerifyCode" />
43             <img src="VerifyCode.ashx" id="Verify_codeImag" alt="点击切换验证码" style="CURSOR: pointer" width="65" height="25" title="点击切换验证码" onclick="ToggleCode(this.id, ‘VerifyCode.ashx‘);return false;" />
44             <input type="button" value="青苹果验证码" onclick="postAjax()" />
45         </div>
46     </form>
47 </body>
48 </html>

【后台】

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7
 8 namespace verifycodeDemo
 9 {
10     public partial class verifycodeDemo : System.Web.UI.Page
11     {
12         protected void Page_Load(object sender, EventArgs e)
13         {
14             string action = Request.Params["action"];
15             string VerifyCodeValue = Request.Params["VerifyCode"];
16             if (action == "comparison")
17             {
18                 string Msg = "true";
19                 //对session中存储的验证码对比
20                 if (HttpContext.Current.Session["dt_session_code"] == null || VerifyCodeValue.ToLower() != HttpContext.Current.Session["dt_session_code"].ToString().ToLower())
21                 {
22                     Msg = "false";//验证码输入不正确
23                 }
24                 Response.Write(Msg);
25                 Response.End();
26             }
27
28         }
29     }
30 }

【ashx文件】

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Drawing;
  4 using System.Drawing.Imaging;
  5 using System.IO;
  6 using System.Linq;
  7 using System.Web;
  8 using System.Web.SessionState;
  9
 10
 11 namespace ESoftMS.Web.Frame
 12 {
 13     /// <summary>
 14     /// VerifyCode 的摘要说明 青苹果(www.cnblogs.com/xinchun)
 15     /// </summary>
 16     public class VerifyCode : IHttpHandler, IRequiresSessionState
 17     {
 18
 19         public void ProcessRequest(HttpContext context)
 20         {
 21             int codeW = 80;
 22             int codeH = 22;
 23             int fontSize = 16;
 24             string chkCode = string.Empty;
 25             //颜色列表,用于验证码、噪线、噪点
 26             Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
 27             //字体列表,用于验证码
 28             string[] font = { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" };
 29             //验证码的字符集,去掉了一些容易混淆的字符
 30             char[] character = { ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘8‘, ‘9‘, ‘a‘, ‘b‘, ‘d‘, ‘e‘, ‘f‘, ‘h‘, ‘k‘, ‘m‘, ‘n‘, ‘r‘, ‘x‘, ‘y‘, ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘J‘, ‘K‘, ‘L‘, ‘M‘, ‘N‘, ‘P‘, ‘R‘, ‘S‘, ‘T‘, ‘W‘, ‘X‘, ‘Y‘ };
 31             Random rnd = new Random();
 32             //生成验证码字符串
 33             for (int i = 0; i < 4; i++)
 34             {
 35                 chkCode += character[rnd.Next(character.Length)];
 36             }
 37             //写入Session
 38             context.Session["dt_session_code"] = chkCode;
 39             //创建画布
 40             Bitmap bmp = new Bitmap(codeW, codeH);
 41             Graphics g = Graphics.FromImage(bmp);
 42             g.Clear(Color.White);
 43             //画噪线
 44             for (int i = 0; i < 1; i++)
 45             {
 46                 int x1 = rnd.Next(codeW);
 47                 int y1 = rnd.Next(codeH);
 48                 int x2 = rnd.Next(codeW);
 49                 int y2 = rnd.Next(codeH);
 50                 Color clr = color[rnd.Next(color.Length)];
 51                 g.DrawLine(new Pen(clr), x1, y1, x2, y2);
 52             }
 53             //画验证码字符串
 54             for (int i = 0; i < chkCode.Length; i++)
 55             {
 56                 string fnt = font[rnd.Next(font.Length)];
 57                 Font ft = new Font(fnt, fontSize);
 58                 Color clr = color[rnd.Next(color.Length)];
 59                 g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 + 2, (float)0);
 60             }
 61             ////画噪点
 62             //for (int i = 0; i < 1; i++)
 63             //{
 64             //    int x = rnd.Next(bmp.Width);
 65             //    int y = rnd.Next(bmp.Height);
 66             //    Color clr = color[rnd.Next(color.Length)];
 67             //    bmp.SetPixel(x, y, clr);
 68             //}
 69             //清除该页输出缓存,设置该页无缓存
 70             context.Response.Buffer = true;
 71             context.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
 72             context.Response.Expires = 0;
 73             context.Response.CacheControl = "no-cache";
 74             context.Response.AppendHeader("Pragma", "No-Cache");
 75             //将验证码图片写入内存流,并将其以 "image/Png" 格式输出
 76             MemoryStream ms = new MemoryStream();
 77             try
 78             {
 79                 bmp.Save(ms, ImageFormat.Png);
 80                 context.Response.ClearContent();
 81                 context.Response.ContentType = "image/Gif";
 82                 context.Response.BinaryWrite(ms.ToArray());
 83             }
 84             catch (Exception)
 85             {
 86
 87             }
 88             finally
 89             {
 90                 g.Dispose();
 91                 bmp.Dispose();
 92             }
 93         }
 94
 95         public bool IsReusable
 96         {
 97             get
 98             {
 99                 return false;
100             }
101         }
102     }
103 }

Demo下载:

http://files.cnblogs.com/xinchun/verifycodeDemo.rar

点滴积累【C#】---验证码,ajax提交,布布扣,bubuko.com

时间: 2024-08-07 16:44:27

点滴积累【C#】---验证码,ajax提交的相关文章

博客园项目-登录(验证码,ajax提交数据,session和cookie)

前端页面 {% load static %} <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content

Ajax提交表单时验证码自动验证 php后端验证码检测

本文通过源码展示如何实现表单提交前,验证码先检测正确性,不正确则不提交表单,更新验证码. 1.前端代码 index.html <!DOCTYPE html> <html> <head> <title>验证码提交自验证</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta htt

jquery ajax提交表单数据的两种方式

jquery ajax提交表单数据的两种方式

django ajax提交避免csrf错误的方法

使用django 防御csrf功能时,ajax提交表单 {{ csrf_token }}加入到data里面,可避免csrf错误.位置如下红色标注: $.ajax({    :,    :{:.,},    :,    :(callback){       callback = jQuery.parseJSON(callback);       (callback.> ){          .()          .(callback[].);          =callback[].- .

JavaWeb开发中form、ajax提交数据Model转化

JavaWeb开发中form.ajax提交数据Model转化 问题 最近学习MongoDB数据库,作为java开发的我,当然需要做个小的web程序来测试一番了.在html中我采取ajax提交方式,因为我要模拟各种类型的数据,基础数据类型.数组.对象等.然而,最终发现了个不同的地方:Form和ajax提交数据,在HttpServletRequest中尽然参数名有所不同. 数据类型 form ajax 基础数据 para=value para=value 数组 para[]={"aaa",

利用jquery进行ajax提交表单和附带的数据

1.获取表单数据: $form.serialize() 2.附带数据:input[status]=1 3.构造url链接:url = $form.attr('action') + '?input[status]=1' 3.ajax提交:$.post(url, post_data, function(res){xxx}, 'json'); 4.后台php接收 $_REQUEST['input'];(input是一个数组存放提交的所有数据)

ajax提交表单

ajax提交表单在项目中常用,前台无论是简单的html.jsp或者是使用了easyui框架,提交表单都会使用到ajax,extjs框架其实也是使用了ajax只不过对其进行了封装了,我们使用的时候就更固定了些. 总的来说ajax提交表单可以分为两种,一种是无返回结果的,就是将表单数据提交给后台,后台处理完就完了:另一种就是有返回结果的,后台执行成功或失败的信息需要返回到前台. 1,无返回结果的 最简单的就是$("#formid").submit();直接将form表单提交到后台. 2,有

关于ajax提交表单

今天主要是四个问题: 1.表单页面元素的获取: 2.按钮的值的获取: 3.按钮的值以变量提交: 4.表单的提交: 获取表单元素时用的是事件委托的方法.{犯的错误:1.用获取表格父级元素的方法获取,没有意识到表单的值是填在value里面的,而表格里面的值直接在th容器里填的 2.在考虑父级元素时没有考虑到它所有的容器都属于他的父级元素                                                                                   

ajax提交富文本,内容被截断,解决方法及思路

问题描述: 使用百度的UEditor富文本插件用于前端富文本编辑,后端使用jsp,提交普通文本没有问题,后来发现在提交某些指定文本时,数据查回的数据出现不完整现象:第一件事就是想到“垃圾编辑器”??,但是此时项目已经上线,再次重构时间成本太高,没办法只好硬着头皮->“调试”??. 解决思路: 前端获取控件内容不完整,开启前端调试:结果是有内容且完整 那完了,前端有,是不是后端没有取到值,调试了一下后端,果然: 我开始怀疑人生了??像这种情况还能怎么办,那只有一种可能了,在向服务器提交时字符被截断