效果:

思路:

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

代码:

【前台】

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="verifycodeDemo.aspx.cs" Inherits="verifycodeDemo.verifycodeDemo" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>青苹果验证码例子</title>
<script src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
//切换验证码
function ToggleCode(obj, codeurl) {
$("#" + obj).attr("src", codeurl + "?time=" + Math.random());
}
//ajax提交后台验证
function postAjax() {
var VerifyCodeValue = $("#txtVerifyCode").val();
$.ajax({
type: 'post',
dataType: "text",
url: "verifycodeDemo.aspx",
data: "action=comparison&VerifyCode=" + VerifyCodeValue,
cache: false,
async: false,
success: function (msg) {
if (msg == "false") {
alert("验证失败!sorry,青苹果");
ToggleCode("Verify_codeImag", "VerifyCode.ashx");
$("#txtVerifyCode").val("");
}
else {
alert("验证成功!hello,青苹果!");
}
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtVerifyCode" />
<img src="VerifyCode.ashx" id="Verify_codeImag" alt="点击切换验证码" style="CURSOR: pointer" width="65" height="25" title="点击切换验证码" onclick="ToggleCode(this.id, 'VerifyCode.ashx');return false;" />
<input type="button" value="青苹果验证码" onclick="postAjax()" />
</div>
</form>
</body>
</html>

【后台】

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace verifycodeDemo
{
public partial class verifycodeDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.Params["action"];
string VerifyCodeValue = Request.Params["VerifyCode"];
if (action == "comparison")
{
string Msg = "true";
//对session中存储的验证码对比
if (HttpContext.Current.Session["dt_session_code"] == null || VerifyCodeValue.ToLower() != HttpContext.Current.Session["dt_session_code"].ToString().ToLower())
{
Msg = "false";//验证码输入不正确
}
Response.Write(Msg);
Response.End();
} }
}
}

【ashx文件】

 using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState; namespace ESoftMS.Web.Frame
{
/// <summary>
/// VerifyCode 的摘要说明 青苹果(www.cnblogs.com/xinchun)
/// </summary>
public class VerifyCode : IHttpHandler, IRequiresSessionState
{ public void ProcessRequest(HttpContext context)
{
int codeW = ;
int codeH = ;
int fontSize = ;
string chkCode = string.Empty;
//颜色列表,用于验证码、噪线、噪点
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
//字体列表,用于验证码
string[] font = { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" };
//验证码的字符集,去掉了一些容易混淆的字符
char[] character = { '', '', '', '', '', '', '', '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' };
Random rnd = new Random();
//生成验证码字符串
for (int i = ; i < ; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
//写入Session
context.Session["dt_session_code"] = chkCode;
//创建画布
Bitmap bmp = new Bitmap(codeW, codeH);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
//画噪线
for (int i = ; i < ; i++)
{
int x1 = rnd.Next(codeW);
int y1 = rnd.Next(codeH);
int x2 = rnd.Next(codeW);
int y2 = rnd.Next(codeH);
Color clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
//画验证码字符串
for (int i = ; i < chkCode.Length; i++)
{
string fnt = font[rnd.Next(font.Length)];
Font ft = new Font(fnt, fontSize);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * + , (float));
}
////画噪点
//for (int i = 0; i < 1; i++)
//{
// int x = rnd.Next(bmp.Width);
// int y = rnd.Next(bmp.Height);
// Color clr = color[rnd.Next(color.Length)];
// bmp.SetPixel(x, y, clr);
//}
//清除该页输出缓存,设置该页无缓存
context.Response.Buffer = true;
context.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds();
context.Response.Expires = ;
context.Response.CacheControl = "no-cache";
context.Response.AppendHeader("Pragma", "No-Cache");
//将验证码图片写入内存流,并将其以 "image/Png" 格式输出
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
catch (Exception)
{ }
finally
{
g.Dispose();
bmp.Dispose();
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}

Demo下载:

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

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

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

    本文通过源码展示如何实现表单提交前,验证码先检测正确性,不正确则不提交表单,更新验证码. 1.前端代码 index.html <!DOCTYPE html> <html> &l ...

  2. python_way day21 Django文件上传Form方式提交,原生Ajax提交字符处啊,Django文件上传之原生Ajax方式、jQuery Ajax方式、iframe方式,Django验证码,抽屉示例,

    python_way day21 1.Django文件上传至Form方式 2.原生Ajax文件上传提交表单 使用原生Ajax好处:不依赖jquery,在发送一个很小的文件或者字符串的时候就可以用原生A ...

  3. javascript表单的Ajax 提交插件的使用

    Ajax 提交插件 form.js 表单的下载地址:官方网站:http://malsup.com/jquery/form/ form.js 插件有两个核心方法:ajaxForm()和ajaxSubmi ...

  4. Ajax 提交KindEditor的数据

    这次我是在EasyUI中使用了KindEditor的编辑器,按照官方给的代码,总是无法获取编辑器里面的值(内容),如下:         KindEditor.ready(function (K) { ...

  5. jquery实现ajax提交表单信息

    最近在思考优化项目,想自己扩展一个jquery自动获取表单中的数据进行ajax提交.本人没有完整性学习jquery,基本上是现学现找,有点困难. 主要是扩展和拼接json转对象 很简单,附上代码: ; ...

  6. ajax提交form表单

    1. ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单. 2. from视图部分 <form id="loginF ...

  7. 【ajax 提交表单】多种方式的注意事项

    在业务中,可能因为表单内容过于庞大,字段过于繁杂,如果人为去拼接的话 ,需要耗费大量的时间和精力,与此同时,代码看上去也是冗余不堪. 所以,提交表单的时候如果能整个表单数据整体提交,那是非常开心的事情 ...

  8. Ajax提交参数的值中带有html标签不能提交成功的解决办法(ASP.NET)

    最近在公司做资源及文章上传功能遇到一个小问题,被坑了好半天. 该功能就类似利用富文本编辑器发布信息,但是用Ajax提交数据,因此提交参数值中不可避免的含有html标签. 在本地运行代码一直没问题,总是 ...

  9. ajax提交form表单资料详细汇总

    一.ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单.通过在后台与服务器进行少量数据交换,ajax 可以使网页实现异步更新.这意味 ...

随机推荐

  1. uva10392 Factoring Large Numbers

    uva10392 Factoring Large Numbers 本文涉及的知识点是,使用线性筛选法得到素数表. Table of Contents 1 题目 2 思路 3 参考 1 题目 ===== ...

  2. 迁移11g Rac中OCR和VOTEDISK

    环境:OEL+oracle rac 11.2.0.3 迁移描述:将ocr和votedisk从+DATE上迁移到+OCR_VOTE上: 操作如下: [root@ora2 ~]$ /u01/app/11. ...

  3. css一些我所不熟练的属性

    <hr />  表示一条横线 css的三种创建方式: 外部样式表 <head> <link rel="stylesheet" type="t ...

  4. 使用moment.js管理时间

    如果在nodejs下 npm install moment 引用模块: var moment = require('moment'); 用法: 当前时间:2015-11-07 18:00:51 mom ...

  5. python编码规范、js编码规范及IDE的检查插件pylint/eslint等

    一.python规范 参考:https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/的风格规范和语 ...

  6. 四、logback日志

    加入在main\resources 创建logback.xml文件 <configuration> <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, ...

  7. Linux 进程学习

    1.linux进程间通讯         继承unix进程间通讯:管道 信号         AT&T :system V IPC 通讯进程只能在单个计算机 :信号量  消息队列 共享内存   ...

  8. Hibernate原生SQL查询数据转换为HQL查询数据方法

    HQL形式:(构造方法不支持timestamp类型) public List<Device> queryByMatherBoardId(String matherBoardId) { St ...

  9. Ubuntu中网络配置问题

    今天,机器做IP变更配置ubuntu网卡的时候出现了: RTNETLINK answers: File exists 网络network service 无法重启 google一下找到  rm etc ...

  10. megalo -- 网易考拉小程序解决方案

    megalo 是基于 Vue 的小程序框架(没错,又是基于 Vue 的小程序框架),但是它不仅仅支持微信小程序,还支持支付宝小程序,同时还支持在开发时使用更多 Vue 的特性. 背景 对于用户而言,小 ...