重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
本篇文章為大家展示了怎么在asp.net中利用ashx生成一個(gè)圖形驗(yàn)證碼,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
1. 寫個(gè)ashx生成圖形驗(yàn)證碼
using System; using System.Collections; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; using System.Web.SessionState; using System.Drawing; namespace usechecknum.ashx { ////// $codebehindclassname$ 的摘要說明 /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class doCreateNum : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string checkCode = GetValidation(5); // 產(chǎn)生5位隨機(jī)驗(yàn)證碼字符 context.Session["Code"] = checkCode; //將字符串保存到Session中,以便需要時(shí)進(jìn)行驗(yàn)證 System.Drawing.Bitmap image = new System.Drawing.Bitmap(70, 22); Graphics g = Graphics.FromImage(image); try { //生成隨機(jī)生成器 Random random = new Random(); //清空?qǐng)D片背景色 g.Clear(Color.White); // 畫圖片的背景噪音線 int i; for (i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true); g.DrawString(checkCode, font, brush, 2, 2); //畫圖片的前景噪音點(diǎn) g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); context.Response.ClearContent(); context.Response.ContentType = "image/Gif"; context.Response.BinaryWrite(ms.ToArray()); } finally { g.Dispose(); image.Dispose(); } } public string GetValidation(int num) { string str = "/upload/otherpic43/ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //"或者寫漢字也行" string validatecode = ""; Random rd = new Random(); for (int i = 0; i < num; i++) { validatecode += str.Substring(rd.Next(0, str.Length), 1); } return validatecode; } public bool IsReusable { get { return false; } } } }
2. 在頁面上顯示驗(yàn)證碼,因?yàn)槲覀兩傻氖菆D形,所以可以直接寫在標(biāo)簽里,我們只要寫段簡(jiǎn)單的腳本就可以點(diǎn)擊鼠標(biāo)切換驗(yàn)證碼了
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="usechecknum._Default" %>驗(yàn)證碼的使用
說了半天,該是時(shí)候看看生成的驗(yàn)證碼長(zhǎng)什么樣了
上述內(nèi)容就是怎么在asp.net中利用ashx生成一個(gè)圖形驗(yàn)證碼,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。