views:

387

answers:

2

Hello!

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?

+4  A: 

Try Implementing IRequiresSessionState interface from namespace.

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

Anuraj
+1 - searching old questions is rarely time wasted. This solved the exact same problem for me too - thanks.
ChrisA
A: 

Your Handler needs to implement IRequiresSessionState.

public class CaptchaHandler : IHttpHandler, IRequiresSessionState
{
...
}
Carl Bergquist