栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.NET使用一般处理程序生成验证码

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

一般处理程序WaterMark.ashx

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.SessionState;  

public class WaterMark : IHttpHandler, IRequiresSessionState  // 要使用session必须实现该接口,记得要导入System.Web.SessionState命名空间
{

    public void ProcessRequest(HttpContext context)
    {
        string checkCode = GenCode(5);  // 产生5位随机字符
        context.Session["Code"] = checkCode; //将字符串保存到Session中,以便需要时进行验证
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(70, 22);
        Graphics g = Graphics.FromImage(image);
        try
        {
            //生成随机生成器
            Random random = new Random();

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

            // 画图片的背景噪音线
            int i;
            for (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.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);

            //画图片的前景噪音点
            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();
        }
    }

    /// 
    /// 产生随机字符串
    /// 
    /// 随机出几个字符
    /// 随机出的字符串
    private string GenCode(int num)
    {
        string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//"选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属价严";
        char[] chastr = str.ToCharArray();
        // string[] source ={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#", "$", "%", "&", "@" };
        string code = "";
        Random rd = new Random();
        int i;
        for (i = 0; i < num; i++)
        {
            //code += source[rd.Next(0, source.Length)];
            code += str.Substring(rd.Next(0, str.Length), 1);
        }
        return code;

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

Web窗体中的代码段:验证码使用img代替

//验证码使用img路径

//刷新验证码,此上个代码基础上加一句

防止浏览器缓存问题,加时间参数


未输入验证码时,弹出请提交验证码文本框

验证码: 

验证码的提交按钮,后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;
using System.Data;

public partial class newscontent : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string newsid = Request.QueryString["newsid"];

            NewsManager nm = new NewsManager();

            News news = nm.SelectById(newsid);

            // 设置新闻主体
            lblTitle.Text = news.Title;
            lblContent.Text = news.Content;
            lblCreateTime.Text = news.CreateTime;

            // 绑定新闻评论
            DataTable dt = new CommentManager().SelectByNewsId(newsid);
            if (dt.Rows.Count == 0)
            {
                // 无新闻评论
                emptydata.Visible = true;
            }
            else
            {
                // 有新闻评论
                emptydata.Visible = false;
                repComment.DataSource = dt;
                repComment.DataBind();
            }
        }
    }

    // 删除按钮
    protected void lbtnDelComment_Click(object sender, EventArgs e)
    {
        // 当前点击的按钮
        LinkButton lb = (LinkButton)sender;
        // 获取传过来的commentId
        string comId = lb.CommandArgument;
        // 删除该评论
        bool b = new CommentManager().Delete(comId);
        if (b)
        {
            // 重新绑定新闻评论
            string newsid = Request.QueryString["newsid"];
            DataTable dt = new CommentManager().SelectByNewsId(newsid);
            if (dt.Rows.Count == 0)
            {
                // 无新闻评论
                emptydata.Visible = true;
                repComment.DataSource = dt;
                repComment.DataBind();
            }
            else
            {
                // 有新闻评论
                emptydata.Visible = false;
                repComment.DataSource = dt;
                repComment.DataBind();
            }
        }
        else {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "");
        }

    }

    // 添加新闻评论
    protected void btnSub_Click(object sender, EventArgs e)
    {
        // 判断验证码是否输入正确
        string code = txtCode.Text.Trim().ToUpper();
        string rightCode = Session["Code"].ToString();
        if (code != rightCode)
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "");
            return;
        }

        // 添加进数据库
        string com_content = txtComment.Text;
        string newsid = Request.QueryString["newsid"];
        string userIp = Request.ServerVariables["REMOTE_ADDR"];
        Comment com = new Comment(com_content, userIp, newsid);
        bool b = new CommentManager().Insert(com);
        if (b)
        {
            // 清空文本框
            txtComment.Text = "";
            txtCode.Text = "";

            // 隐藏"该新闻目前暂无评论!"
            emptydata.Visible = false;

            // 重新绑定新闻评论
            repComment.DataSource = new CommentManager().SelectByNewsId(newsid);
            repComment.DataBind();
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "");
        }
    }

    // 根据session的值显示或者隐藏删除评论的按钮
    protected void repComment_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            // 判断session的值显示或者隐藏删除评论的按钮
            if (Session["admin"] != null && Session["admin"].ToString() == "niunan")
            {
                ((LinkButton)e.Item.FindControl("lbtnDelComment")).Visible = true;
            }
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/910758.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号