效果:

思路:

借用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. 性能问题: SQL*Net message from client 等待时间太长

    今天我终于自己遇到了这个问题, PO form 打不开了, 看了下 trace 发现 SQL*Net message from client 等待时间太长. 但是这不可能是网络问题, 这个环境是在我电 ...

  2. Spring @Autowired 注解不生效

    @Autowired默认不生效.为了生效,需要在xml配置:<context:annotation-config> 注解一<context:component-scan base-p ...

  3. Python 爬取外文期刊论文信息(机械 仪表工业)

    NSTL国家科技图书文献中心    2017  机械 仪表工业  所有期刊论文信息 代码比较随意,不要介意 第一步,爬取所有期刊链接 #coding=utf-8 import time from se ...

  4. ShopNC B2B2C多用户商城2014商业版,带微商城

    据说价值7000RMB,咱们好站长资源网友分享出来的,非常感谢分享这么好的源码.此套ShopNC B2B2C多用户商城源码是2014版的,带有微商城,源码我们安装测试基本没发现啥问题,这两天将会完全免 ...

  5. XAMPP + Xdebug+Zend Studio

    建立php开发环境(XAMPP + Xdebug+Zend Studio) 大家知道,运行php可以在apache上运行,但是要在apache上配置php解释器模块,懒得麻烦.就用XAMPP吧,它已经 ...

  6. tornado 多进程模式

    https://www.douban.com/note/217901726/ 官方文档的helloworld实例中的启动方法: if __name__ == "__main__": ...

  7. C#时间的味道——任时光匆匆我只在乎你

    如果没有遇见你,我将会是在哪里?日子过的怎么样人生是否要珍惜...任时光匆匆我只在乎你,心甘情愿感染你的气息,人生几何能得到知己...一首邓丽君的<我只在乎你>不禁令我唏嘘不已,这些年离我 ...

  8. 今天科普一下 iOS马甲包审核以及常见审核问题

    一.什么是马甲包 马甲包是利用App store 规则漏洞,通过技术手段,多次上架同一款产品的方法.马甲包和主产品包拥有同样的内容和功能,除了icon和应用名称不能完全一致,其他基本一致.    二. ...

  9. eslint for...in 报错处理

    示例代码: <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF ...

  10. Vue 组件通信(子组件向父组件传递数据)

    1.自定义事件 <!DOCTYPE html> <html lang="zh"> <head> <meta charset="U ...