欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET生成驗證碼的方法

 更新時間:2020年05月27日 16:29:14   作者:南 墻  
這篇文章主要為大家詳細(xì)介紹了ASP.NET生成驗證碼的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了ASP.NET生成驗證碼的具體代碼,供大家參考,具體內(nèi)容如下

首先,添加一個一般處理程序

注釋很詳細(xì)了,有不懂的歡迎評論

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構(gòu)造Image
  Image img = new Bitmap(100, 60);
  //Graphics繪畫Image
  Graphics graphics = Graphics.FromImage(img);

  Random random = new Random(DateTime.Now.Millisecond);
  //驗證碼的四位數(shù)
  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);
  //把生成的隨機數(shù)變成字符串,通過char進(jìn)行轉(zhuǎn)換
  string validCode = string.Format($"{(char)charNum1}{(char)charNum2}{(char)charNum3}{(char)charNum4}");
  //放進(jìn)Session進(jìn)行存儲,記得繼承接口,否則瘋狂報空指針
  context.Session["verification_Code"] = validCode;
  //字體的大小和類別
  Font font = new Font("宋體", 24);
  //隨機的顏色
  Brush brush1 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
  //DrawString的四個參數(shù),第一個是要寫的字符,第二個是字體,第三個是顏色,第四個是坐標(biāo)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 id="form1" runat="server">
 <div>
  <asp:Image ID="Image1" runat="server" ImageUrl="~/Handler1.ashx" />
 </div>
 </form>
</body>
</html>

效果圖

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論