【C#】一般處理程序ashx生成驗證碼、繪製驗證碼,傳遞數據

SNAGHTMLe288f1

注意:要使用Session需要引用System.Web.SessionState命名空間,讓ashx類繼承IRequiresSessionState 接口

<%@ WebHandler Language="C#" Class="BackImage" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class BackImage : IHttpHandler,IRequiresSessionState {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/jpeg";//規定返回一個圖片
        //生成一個驗證碼
        string strCheck = "";
        Random r = new Random();
        for (int i = 1; i <= 4; i++)
        {
            string s = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            int start = r.Next(61);
            strCheck += s.Substring(start, 1);
        }
        //將驗證碼畫在圖片上
        Bitmap img = new Bitmap(40,20);//造一個空白畫板
        Graphics gr=Graphics.FromImage(img);//定義一個畫板img的畫筆
        SolidBrush brush=new SolidBrush(Color.White);//定義一個白色的刷子
        gr.FillRectangle(brush, 0, 0, 40, 20); //畫一個白色長方形背景
        
        Font font=new Font("宋體",13,FontStyle.Italic);//定義一個繪製字符串時,用的字體
        brush.Color = Color.Red;//改變刷子的顏色,與背景區別
        gr.DrawString(strCheck,font,brush,0,0);

        //將此圖像保存到指定的流中
        img.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

        //定義一個Session傳遞數據
        context.Session["strCheck"] = strCheck;
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

SNAGHTMLe51fc4

注意實現訪問隨機ashx類文件的方式,和訪問Session信息的方式(直接調用Session)

SNAGHTMLea6136

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章