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

动态加载验证码

1.创建一般应用程序ashx

<%@ WebHandler Language="C#" Class="YZM" %> 
 
using System; 
using System.Web; 
 
public class YZM : IHttpHandler,System .Web.SessionState .IRequiresSessionState{ 
     
    public void ProcessRequest (HttpContext context) { 
       //动态生成图片 
        context.Response.ContentType = "image/JPEG"; 
        using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(100, 30)) 
        { 
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) 
            { 
                /*
                 g.DrawString("验证码", new System.Drawing.Font("宋体", 10), System.Drawing.Brushes .Red , new System.Drawing.PointF(0, 0));
                 bitmap .Save (context .Response .OutputStream ,System .Drawing.Imaging.ImageFormat .Jpeg) ;
                 */ 
                //动态产生随机数 
                Random rand = new Random(); 
                int code = rand.Next(); 
                string strCode = code.ToString(); 
                HttpContext.Current.Session["Code"] = strCode; 
                g.DrawString(strCode, new System.Drawing.Font("宋体", 12), System.Drawing.Brushes.Green, new System.Drawing.PointF(0, 0)); 
                bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); 
            } 
        } 
    } 
   
  
    public bool IsReusable { 
        get { 
            return false; 
        } 
    } 
 
 
     

2.在aspx中调用Session中存储的验证码

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
 
public partial class 验证码 : System.Web.UI.Page 

    protected void Page_Load(object sender, EventArgs e) 
    { 
 
    } 
    protected void Button1_Click(object sender, EventArgs e) 
    { 
        string yzm = Convert.ToString(Session ["Code"]); 
        Response.Write(yzm); 
        if (yzm==TextBox1 .Text ) 
        { 
            Response.Write("验证码正确"); 
        } 
        else 
        { 
            Response.Write("验证码不正确,请重新输入"); 
            TextBox1.Text = ""; 
        } 
    } 


摘自 编程爱好者
补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,