随机验证码.ashx

ValidateCode.ashx

<%@ WebHandler Language="C#" class="ValidateCode" %>

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Drawing.Drawing2D;
using System.Drawing;

public class ValidateCode : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            this.CreateCheckCodeImage(GenerateCheckCode(context), context);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private string GenerateCheckCode(HttpContext context)
        {
            int number;
            char code;
            string checkCode = String.Empty;

System.Random random = new Random();

for (int i = 0; i < 6; i++)
            {
                number = random.Next();

if (number % 2 == 0)
                    code = (char)(‘0‘ + (char)(number % 10));
                else if (number % 3 == 0)
                    code = (char)(‘A‘ + (char)(number % 26));
                else
                    code = (char)(‘a‘ + (char)(number % 26));
                checkCode += code.ToString();
            }

context.Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
            //也可以存到Seesion里.        
            //context.Session["CheckCode"] = checkCode;   
            return checkCode;
        }
        private void CreateCheckCodeImage(string checkCode, HttpContext context)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;
            Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器   
                Random random = new Random();

//清空图片背景色      
                g.Clear(Color.White);

//画图片的背景噪音线  
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f,

true);
                g.DrawString(checkCode, font, brush, 2, 2);

//画图片的前景噪音点    
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

//画图片的边框线     
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                context.Response.ClearContent();
                context.Response.ContentType = "image/Gif";
                context.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }

}
    }
}

页面:

<img src="ValidateCode.ashx" title="看不清?点击刷新" style="cursor:pointer" onclick="this.src=‘ValidateCode.ashx?_=‘+Math.random()">

后台代码:

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;

public partial class Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

if (Request.Cookies["CheckCode"] == null)

{

lblMessage.Text = "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";

lblMessage.Visible = true;

return;

}

if (String.Compare(Request.Cookies["CheckCode"].Value, txtCheckCode.Text, true) != 0)

{

lblMessage.Text = "验证码错误,请输入正确的验证码。";

lblMessage.Visible = true;

return;

}

//在这执行下一步

//CheckCode是存到Session里的

//if (Session["CheckCode"] != null)             //{             //    if (String.Compare(Session["CheckCode"].ToString(), txtCheckCode.Text.Trim(), true) != 0)             //    {             //        lblMessage.Text = "验证码错误,请输入正确的验证码。";             //        lblMessage.Visible = true;             //        return;             //    }             //    else             //    {//在这执行下一步             //    }             //}         }     }

时间: 2024-11-07 15:06:41

随机验证码.ashx的相关文章

生成6位的随机验证码

要求:生成6位的字母和数字组成的随机验证码. 实例1: 1 import random 2 identify_code='' 3 for i in range(1): 4 for j in range(6): 5 if i==j: 6 code=chr(random.randint(65,90)) 7 else: 8 code=random.randint(0,9) 9 identify_code+=str(code) 10 11 print(identify_code) 实例2: 1 impo

Django之路 - 实现登录随机验证码

登录验证码是每个网站登录时的基本标配,网上也有很多相应的文章, 但是从生成验证码到 应用到自己的网站上的全步骤,并没有看到很多, 为了节约大家的时间,我把整体步骤写下来, 即拿即用哈 1. 生成随机验证码  随机验证码代码 2. 如何应用到你的django项目中 整个验证码的流程如下 用户访问登录页面,你的后台程序在给用户返回登录页面时,同时生成了验证码图片 用户输入账户信息和验证码数字,提交表单 后台判断用户输入的验证码和你生成的图片信息是否一致,如果一致,就代表验证码是没有问题的 问题就卡在

学习python:实例2.用PIL生成随机验证码

效果: 代码: # 生成随机验证码图片 import string from random import randint, sample from PIL import Image, ImageDraw, ImageFont, ImageFilter # Image 负责处理图片 # ImageDraw 画笔 # ImageFont 文字 # ImageFileter 滤镜 # 定义变量 img_size = (150,50)        # 定义画布大小 img_rgb = (255,255

输出随机验证码图片

1 /** 2 * //输出随机验证码图片:CAPTCHA图像 3 */ 4 public class ServletDemo1 extends HttpServlet { 5 private static final long serialVersionUID = 1L; 6 7 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOEx

随机验证码

import java.awt.image.BufferedImage; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletExc

利用random生成6位随机验证码

使用random生成6位随机验证码 #!/usr/bin/env python # _*_ coding:utf-8 _*_ import random code = [] for i in range(6):     #可在此处改变条件表达式来调整生成数字的机率     if i == random.randint(0,5):         # 如果随机数与0-5中的随机数相等,生成数字验证码        code.append(str(random.randint(0,9)))     

iPhone:iOS界面,本地生成随机验证码

本文博客,模仿杰瑞教育的一篇博文,并在它的基础上,进行了些许更改.同时在重写的过程中,对自己忽略的地方,进行了重新认识,受益匪浅.文章来源:http://www.cnblogs.com/jerehedu/p/4527707.html 其实这个功能,并不是很实用,但是,对于我们梳理细小的知识点,还是很有必要的. 一,首先,我们需要自定义一个view,这样,我们将图形绘制在里面,init这个view的时候,就可以直接显示了,以后再遇到,就可以“拿来主义”了. codeView.h @property

实现随机验证码

实现随机验证码 1 #生成随机验证码 2 import random 3 temp = "" 4 for i in range(6): 5 num = random.randrange(0,4) 6 if num == 1 or num == 3: 7 rad2 = random.randrange(0,9) 8 temp = temp + str(rad2) 9 else: 10 rad1 = random.randrange(65,91) 11 c1 = chr(rad1) 12

生成随机验证码的方法

1.借助列表 import random def random_code(): random_list = [] for i in range(4): ra = random.randrange(4) if ra == i: random_list.append(chr(random.randrange(97,122))) else: random_list.append(str(random.randrange(0,9))) code = "".join(random_list) r