点滴积累【C#】---验证码,ajax提交
2024-10-19 03:32:19
效果:
思路:
借用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
最新文章
- [更新设计]跨平台物联网通讯框架ServerSuperIO 2.0 ,功能、BUG、细节说明,以及升级思考过程!
- H TC並沒有成為下一個摩托羅拉或諾基亞。
- flash的读写与擦除
- C#:基于WMI查询USB设备信息 及 Android设备厂商VID列表
- GJM : Unity3D结合ZXING制作二维码识别
- 关于sublime text2
- tar 打包命令
- jQuery对表单、表格的操作及更多应用(上:表单应用)
- 水题 ZOJ 3880 Demacia of the Ancients
- android edittext不弹出软键盘
- python手记(32)
- python读取EXCLE文件数据
- ViewPageAsImage
- Best packages for data manipulation in R
- 神奇的RAC宏
- 【Django】 视图层说明
- FTP传输文件被破坏的问题(Linux、Busybox)
- 浅谈CSRF漏洞
- python之restful api(flask)获取数据
- 潭州课堂25班:Ph201805201 爬虫基础 第九课 图像处理- PIL (课堂笔记)