C#会话未从HTTPHandler保存

Pat*_*ick 2 c# session captcha httphandler

我有一个HTTPHandler,只要请求captcha.ashx页面,就会向用户生成一个Captcha图像.它的代码很简单:

        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();
Run Code Online (Sandbox Code Playgroud)

然后在我的常规网站上,我得到以下内容:

...
<img id="securityCode" src="captcha.ashx" alt="" /><br />
<a href="javascript:void(0);" onclick="javascript:refreshCode();">Refresh</a>
...
Run Code Online (Sandbox Code Playgroud)

这非常有效,只要请求captcha.ashx页面,就会生成图像并将其发送回用户.我的问题是HTTPHandler没有保存会话?我试图从正常页面恢复会话,但我只有一个例外,说它不存在,所以我打开Trace看看哪些会话是活动的,它没有列出HTTPHandler创建的会话(验证码).

HTTPHandler使用IReadOnlySessionState与会话进行交互.HTTPHandler是否只具有读访问权限,因此不存储会话?

Anu*_*raj 6

尝试从命名空间实现IRequiresSessionState接口.

查看此链接:http://anuraj.wordpress.com/2009/09/15/how-to-use-session-objects-in-an-httphandler/