Using reCAPTCHA with ASP.NET and C#

I’ve only recently worked with reCAPTCHA, but I was that impressed with it that I thought it deserved a tutorial. Getting the captcha itself into your web page is extremely easy, and is sufficiently documented on the reCAPTCHA site. This article will instead focus on how to validate the input from a captcha control using their web service without creating or borrowing a custom control. Much of the code used here is based on code found at googlecode.

There are three main stages to this. Firstly we create an HttpWebRequest object that we can use to request a response from the web service, and write our parameters for the web method to the request stream. We then get a response using the request and then read the response stream. Finally, we parse the result, and decide whether the captcha was solved.

Firstly, we’ll create a web request using the static method Create in WebRequest, and set it’s properties so that it will work with the web service. As always, I’ve omitted any try/catch statements so that the point of the tutorial is clearer:

  1. string PRIVATE_KEY = "put your reCAPTCHA private key here";
  2. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
  3.     "");
  5. /*
  6. This string will be written to the request stream, and contains
  7. all the parameters required by the web service
  8. */
  9. string body = String.Format(
  10.     "privatekey={0}&remoteip={1}&challenge={2}&response={3}",
  11.     PRIVATE_KEY, Page.Request.UserHostAddress == "::1" ?
  12.     "" : Page.Request.UserHostAddress,
  13.     Page.Request.Form["recaptcha_challenge_field"],
  14.     Page.Request.Form["recaptcha_response_field"]);
  16. // Encode the string using UTF8
  17. bodyBytes = System.Text.Encoding.UTF8.GetBytes(body);
  19. // Set up the required request properties
  20. request.Method = "POST";
  21. request.ContentType = "application/x-www-form-urlencoded";
  22. request.ContentLength = bodyBytes.Length;
  23. request.ProtocolVersion = new Version("1.0");
  25. // Write to the request stream
  26. s = request.GetRequestStream();
  27. s.Write(bodyBytes, 0, bodyBytes.Length);
  28. s.Close();

Next we need to get a response from the web service, and read the response stream into a string:

  1. HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
  2. Stream s2 = resp.GetResponseStream();
  3. StreamReader sr = new StreamReader(s2);
  4. string respString = sr.ReadToEnd();
  5. sr.Close();

The response string from the web service is in the format [boolean]\n[errorCode] where boolean is [true|false] and errorCode is a text string explaining any errors. Error codes are well documented on the reCAPTCHA site. For simplicity’s sake, we’re just going to parse the first line which will be true if the captcha was solved, and false if it was not:

  1. string[] respParams = respString.Split(new char[] { '\n' });
  3. if (Boolean.Parse(respParams[0]))
  4. {
  5.     // The captcha was solved.
  6. }
  7. else
  8. {
  9.     // The captcha was not solved.
  10. }

There you have it. Of course, the whole thing needs to be try/catch/finally-ized very thoroughly, there are a couple of streams that will need disposing of and while I’m sure reCATCHA’s servers are extremely reliable, there is a chance they could go down, meaning an exception at request.GetResponse().

So there you go, at the time of writing, reCAPTCHA have very few examples of captcha use in ASP.NET, I hope this helps to get some people up and running with their services.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • LinkedIn
  • Technorati