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, 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();

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?

13.10.2009 14:28:40
2 ОТВЕТА
РЕШЕНИЕ

Try Implementing IRequiresSessionState interface from namespace.

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

6
13.10.2009 14:32:49
+1 - searching old questions is rarely time wasted. This solved the exact same problem for me too - thanks.
ChrisA 4.05.2010 18:10:17

Your Handler needs to implement IRequiresSessionState.

public class CaptchaHandler : IHttpHandler, IRequiresSessionState
{
...
}
1
13.10.2009 14:37:43