加入收藏 | 设为首页 | 会员中心 | 我要投稿 河北网 (https://www.hebeiwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

ASP.NET生成验证码的方法

发布时间:2020-06-17 06:12:22 所属栏目:编程 来源:站长网
导读:起首,添加一个一样平常处理赏罚措施 注释很具体了,有不懂的接待评述 using System;using System.Collections.Generic;using System.Drawing;using System.Linq;using System.Web;using System.Web.SessionState;namespace Project_Practice{ /// summary /// Han

起首,添加一个一样平常处理赏罚措施

注释很具体了,有不懂的接待评述

using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; using System.Web.SessionState; namespace Project_Practice { /// <summary> /// Handler1 的择要声名 /// </summary> public class Handler1 : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { //选取的颜色 Color[] colors = { Color.White }; //通过Bitmap结构Image Image img = new Bitmap(100, 60); //Graphics绘画Image Graphics graphics = Graphics.FromImage(img); Random random = new Random(DateTime.Now.Millisecond); //验证码的四位数 int charNum1 = random.Next('0', '9' + 1); int charNum2 = random.Next('0', '9' + 1); int charNum3 = random.Next('0', '9' + 1); int charNum4 = random.Next('0', '9' + 1); //把天生的随机数酿成字符串,通过char举办转换 string validCode = string.Format($"{(char)charNum1}{(char)charNum2}{(char)charNum3}{(char)charNum4}"); //放进Session举办存储,记得担任接口,不然猖獗报空指针 context.Session["verification_Code"] = validCode; //字体的巨细和种别 Font font = new Font("宋体", 24); //随机的颜色 Brush brush1 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]); //DrawString的四个参数,第一个是要写的字符,第二个是字体,第三个是颜色,第四个是坐标x,y graphics.DrawString(((char)charNum1).ToString(), font, brush1, 7, -3); Brush brush2 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]); graphics.DrawString(((char)charNum2).ToString(), font, brush2, 26, -9); Brush brush3 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]); graphics.DrawString(((char)charNum3).ToString(), font, brush3, 50, 0); Brush brush4 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]); graphics.DrawString(((char)charNum4).ToString(), font, brush4, 70, -7); //生涯,名目 context.Response.ContentType = "image/jpeg"; img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); //开释资源 graphics.Dispose(); img.Dispose(); } public bool IsReusable { get { return false; } } } }

一个web窗体

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="verification_Code.aspx.cs" Inherits="Project_Practice.verification_Code" %> <!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> </head> <body> <form runat="server"> <div> <asp:Image runat="server" ImageUrl="~/Handler1.ashx" /> </div> </form> </body> </html>

结果图

(编辑:河北网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读