我有一个 HTTPHandler,它会在请求 captcha.ashx 页面时向用户生成验证码图像。它的代码很简单:
CaptchaHandler handler = new CaptchaHandler();
Random random = new Random();
string[] fonts = new string[4] { "Arial", "Verdana", "Georgia", "Century Schoolbook" };
string code = Guid.NewGuid().ToString().Substring(0, 5);
context.Session.Add("Captcha", code);
Bitmap imageFile = handler.GenerateImage(code, 100, 70, fonts[random.Next(0,4)]);
MemoryStream ms = new MemoryStream();
imageFile.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] buffer = ms.ToArray();
context.Response.ClearContent();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(buffer);
context.Response.Flush();
然后在我的常规网站上,我得到了以下信息:
...
<img id="securityCode" src="captcha.ashx" alt="" /><br />
<a href="javascript:void(0);" onclick="javascript:refreshCode();">Refresh</a>
...
这非常有效,只要请求 captcha.ashx 页面,就会生成图像并将其发送回用户。我的问题是 HTTPHandler 不保存会话?我试图从正常页面取回会话,但我只有一个异常说它不存在,所以我打开 Trace 以查看哪些会话处于活动状态并且它没有列出 HTTPHandler 创建的会话(验证码)。
HTTPHandler 使用 IReadOnlySessionState 与会话进行交互。HTTPHandler 是否只有读取权限,因此不存储会话?