0

I'm stuck while experimenting with captcha handler in asp.net, any help would be appreciated. Imagine we have such a handler:

public void ProcessRequest(HttpContext context)
{
    var text = generateText();
    using (var image = generateImage(text))
    {
        context.Response.Clear();
        context.Response.ContentType = "image/jpeg";
        context.Session.Add("captcha", text);
        image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
    }
}

then in some default.aspx we put:

<img src="<%=CaptchaImageUrl %>"/>
<p><%=Context.Session["captcha"]%></p>

meaning that we would like to show captcha image and check captcha value stored in session. But the problem is that current session value in default.aspx is outdated by the side of captcha handler, and

<p><%=Context.Session["captcha"]%></p>

will always return the previous captcha value. Any suggestions?

mumu2
  • 661
  • 1
  • 5
  • 15

1 Answers1

0

You are storing the captcha in session only when the image is requested by the browser. But you are displaying the session value in page, which happens before the image is requested from the browser.

This is the reason why you see the previous captcha in the page.

To fix this, I would recommend to move the generateText to the page and let the page store this value in session. The handler would just pick the value from session, construct the image and render it.

Ramesh
  • 13,043
  • 3
  • 52
  • 88