效果:

思路:

借用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. BlackBerry10 开发环境搭建

    最近开始学习BlackBerry10的开发,黑莓10系统是2013年1月30日黑莓公司正式发布的,目前网上资料比较少,这篇博客的内容基本上是按照官网上的文档写的.BlackBerry10目前支持C/C ...

  2. Xcode no visible @interface for XXX declares

    出现如上面的错误, 是因为没有找到这个方法, 要自己写一个这样的方法 , 如果这是个类目的方法的话,  需要在Target->Linking->Other Linker Flags中添加- ...

  3. SQL手工注入小结

    第一步先把IE菜单=>工具=>Internet选项=>高级=>显示友好 HTTP 错误信息前面的勾去掉.否则,不论服务器返回什么错误,IE都只显示为HTTP 500服务器错误, ...

  4. C#动态调用webservice方法

    摘 自: http://www.hao5191.cn/a/chengxukaifa/c_/20130109/115819.html using System; using System.Collect ...

  5. idea 设置jetty进程jvm参数

    /** * MyEclipse6.5通过Jetty跑Web应用时提示OutOfMemoryError: PermGen space的解决办法 * @see ---------------------- ...

  6. escape(s, t)函数的实现

    https://item.taobao.com/item.htm? spm=686.1000925.0.0.9TTLHO&id=535006878999 <span style=&quo ...

  7. Python描写叙述符(descriptor)解密

    Python中包括了很多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装饰器(decorator).对于大部分特性来说,这些" ...

  8. JMeter 十六:加密处理

    假设采用MD5进行加密 JMeter 内置的没有MD5加密方法.网上有说采用__MD5函数的,但是我在 Jmeter 2.13 以及 Jmeter 3.2 版本上都没有找到这个函数,官方文档也没有看到 ...

  9. 让Vs2013 完美支持EF6.1 Code First with Oracle 2015年12月24日更新

    本文是对下文的补充,切勿以为我是全盘复制哦 连接: http://www.cnblogs.com/wlflovenet/p/4187455.html Normal 0 7.8 磅 0 2 false ...

  10. vue vue-router 使用注意事项

    1.$router和$route区别 this.$router 访问路由器,实现路由的跳转等功能. this.$route 实现访问当前路由,$route.query (如果 URL 中有查询参数). ...