当前位置:编程学习 > asp >>

ValidNumber.ashx验证码

ValidNumber.ashx 代码:

<%@ WebHandler Language="C#" Class="ValidNumber" %>

using System;
using System.Web;
using System.Web.SessionState; //第一步:导入此命名空间
public class ValidNumber : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        //种子
        string[] strlist = new[]
        {
            "a","b","c","d","1","2","3","4","5","6","7","8","9","0","q","w","e","r","t","y","u","i","o","p","z","x","n","v","W","Q","B","A","D","D","F","G","H","J","K","L"
        };

        //生成随机数
        string[] list = new string[4];
        Random rd = new Random(DateTime.Now.Millisecond * 100000);
        for (int i = 0; i < 4; i++)
        {
            list[i] = strlist[rd.Next(strlist.Length)];
            System.Threading.Thread.Sleep(5);
        }

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < 4; i++)
        {
            sb = sb.Append(list[i]);
        }
        HttpContext.Current.Session["validNumber"] = sb;
        //创建一张图片
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(list.Length * 15, 40);
        //创建画布
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
        //清空背景色,并添充成白色
        g.Clear(System.Drawing.Color.White);

        //噪声线
        for (int i = 0; i < 20; i++)
        {
            Random rds = new Random();

            float x1 = rds.Next(image.Width - 1);
            float x2 = rds.Next(image.Width - 1);
            float y1 = rds.Next(image.Height - 1);
            float y2 = rds.Next(image.Height - 1);
            System.Threading.Thread.Sleep(5);
            g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
        }
        System.Drawing.Font f = new System.Drawing.Font("黑体", 25, System.Drawing.GraphicsUnit.Pixel);
        System.Drawing.Brush bs = new System.Drawing.SolidBrush(System.Drawing.Color.Red);

        g.DrawString(sb.ToString(), f, bs, 5, 5);
        //当前请求输出的类型
        HttpContext.Current.Response.ContentType = "image/jpeg";
        //保存到输出流
        image.Save(HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

        g.Dispose();
        image.Dispose();

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

页面调用时 <img src="ValidNumber.ashx" alt="图片验证码" /> 但是回发session值改变页面图片没变,暂无比较理想的解决办法,提交时后台用  Response.Write("<script> window.location.href=window.location.href</script>")  刷新下页面。欢迎指教,有没有好点的用法。

 


摘自 BQL_Email的专栏

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,