要能夠在泛型處理常式中存取工作階段變數(Session Variable),其類別必須實作 System.Web.SessionState 命名空間中的 IRequiresSessionState 介面。如下所示者即是一例:
| <%@ WebHandler Language="C#" Class="confirm" %> //---------------------------------------------------------------------------- //程式功能 圖文驗證模組範例 - 產生圖型 // //備註說明 需先產生 Session["confirm"] // 範例圖檔僅有 0 ~ 9 的圖型 //---------------------------------------------------------------------------- using System; using System.Web; using System.IO; using System.Web.SessionState; public class confirm : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { MemoryStream gdata = new MemoryStream(); BuildImage bd_img = new BuildImage(); string mdata = ""; mdata = context.Session["confirm"].ToString(); // 取得驗證圖型的資料(設定驗證圖型尺寸及驗證字串) gdata = bd_img.GenerateImage(200, 54, mdata); // 設定輸出格式 context.Response.ContentType = "image/png"; // 送出資料內容 context.Response.BinaryWrite(gdata.ToArray()); } public bool IsReusable { get { return false; } } } |
最後提醒大家,於泛型處理常式 .ashx 中,請務必在 Session、Request 與 Response 之前均要加上 context. 才能使用。
章立民研究室
本文節錄自 “ASP.NET 3.5 圖表與實務案例模組大全”一書