ASP.NET Methods of generating captcha


The example of this article is shared for you ASP.NET Generate the specific code of verification code, for your reference, the specific content is as follows

First, add a general handler

The notes are very detailed. Please comment if you don’t understand

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace Project_Practice
 /// <summary>
 ///Summary of handler1
 /// </summary>
 public class Handler1 : IHttpHandler,IRequiresSessionState

 public void ProcessRequest(HttpContext context)
  //Selected color
  Color[] colors = { Color.White };
  //Image construction by bitmap
  Image img = new Bitmap(100, 60);
  //Graphics drawing image
  Graphics graphics = Graphics.FromImage(img);

  Random random = new Random(DateTime.Now.Millisecond);
  //Four digits of captcha
  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);
  //The generated random number into a string, through the char conversion
  string validCode = string.Format($"{(char)charNum1}{(char)charNum2}{(char)charNum3}{(char)charNum4}");
  //Put it into the session for storage. Remember to inherit the interface. Otherwise, it will report null pointer crazily
  context.Session["verification_Code"] = validCode;
  //Font size and category
  New font, font = font;
  //Random colors
  Brush brush1 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
  //The four parameters of drawstring: the first is the character to be written, the second is the font, the third is the color, and the fourth is the coordinates 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);
  //Save, format
  context.Response.ContentType = "image/jpeg";
  img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
  //Releasing resources

 public bool IsReusable
  return false;

A web form

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="verification_Code.aspx.cs" Inherits="Project_Practice.verification_Code" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <form runat="server">
  <asp:Image ID="Image1" runat="server" ImageUrl="~/Handler1.ashx" />

design sketch

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.