1. 程式人生 > 程式設計 >ASP.NET生成驗證碼的方法

ASP.NET生成驗證碼的方法

本文例項為大家分享了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 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(),brush2,26,-9);
  Brush brush3 = new SolidBrush(colors[random.Next(0,colors.Length - 1)]);
  graphics.DrawString(((char)charNum3).ToString(),brush3,50,0);
  Brush brush4 = new SolidBrush(colors[random.Next(0,colors.Length - 1)]);
  graphics.DrawString(((char)charNum4).ToString(),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 id="form1" runat="server">
 <div>
  <asp:Image ID="Image1" runat="server" ImageUrl="~/Handler1.ashx" />
 </div>
 </form>
</body>
</html>

效果圖

ASP.NET生成驗證碼的方法

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。