开发者

C# Session not saved from HTTPHandler

I have a HTTPHandler that produces a Captcha image to the user whenever the captcha.ashx page is requested. The code for it is simple:

        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, 开发者_如何学JAVA5);
        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();

Then on my regular website, i got the following:

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

This works perfectly, the image is generated and sent back to the user whenever the captcha.ashx page is requested. My problem is that the HTTPHandler doesn't save the session? I tried to get the session back from the normal page but i only got an exception saying that it didn't exist, so i turned on Trace to see what sessions that is active and it doesn't list the session that the HTTPHandler created (Captcha).

The HTTPHandler uses IReadOnlySessionState to interact with the sessions. Does the HTTPHandler only have read-access and thus not storing the session?


Try Implementing IRequiresSessionState interface from namespace.

Check this link : http://anuraj.wordpress.com/2009/09/15/how-to-use-session-objects-in-an-httphandler/


Your Handler needs to implement IRequiresSessionState.

public class CaptchaHandler : IHttpHandler, IRequiresSessionState
{
...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜