本篇内容介绍了“ASP.NET如何生成验证码”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
本文实例为大家分享了ASP.NET生成验证码的具体代码,供大家参考,具体内容如下
首先,添加一个一般处理程序
注释很详细了,有不懂的欢迎评论
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 brush2 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
//DrawString的四个参数,第一个是要写的字符,第二个是字体,第三个是颜色,第四个是坐标x,y
graphics.DrawString(((char)charNum1).ToString(), font, brush2, 7, -3);
Brush brush3 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum2).ToString(), font, brush3, 26, -9);
Brush brush4 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum3).ToString(), font, brush4, 50, 0);
Brush brush5 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum4).ToString(), font, brush5, 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 id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Handler1.ashx" />
</div>
</form>
</body>
</html>
效果图
“ASP.NET如何生成验证码”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。