Before using Google Captcha (reCAPTCHA), you need to Create a reCAPTCHA key by providing a domain name via http://www.google.com/recaptcha/whyrecaptcha. Let’s store the Public Key and Private Key in the appSettings section of the web.config then we will read these appSetting in code behind. Your web.config is similar to below:
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="false" targetFramework="4.0" /> </system.web> <appSettings> <add key="reCAPTCHAPublicKey" value="your_public_key"/> <add key="reCAPTCHAPrivateKey" value="your_private_key"/> </appSettings> </configuration> |
You also need to download the Google Captcha (reCAPTCHA) ASP.NET library via http://code.google.com/p/recaptcha/downloads/list?q=label:aspnetlib-Latest.
After got the reCAPTCHA keys and downloaded the reCAPTCHA ASP.NET library, let’s add a reference to the Recaptcha.dll on your web application.
Below is full source code that places a Google Captcha on a asp.net page:
C# – ASP.NET Implement Google Captcha
+ aspx source code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="google-captcha.aspx.cs" Inherits="google_captcha" %> <%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label Visible="false" ID="lblResult" runat="server" /> <recaptcha:RecaptchaControl ID="recaptcha" runat="server" /> <asp:Button ID="btnSubmit" runat="server" Text="Test Google Captcha" OnClick="btnSubmit_Click" /> </div> </form> </body> </html> |
+ aspx.cs source code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class google_captcha : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { recaptcha.PublicKey = System.Configuration.ConfigurationManager.AppSettings["reCAPTCHAPublicKey"].ToString(); recaptcha.PrivateKey = System.Configuration.ConfigurationManager.AppSettings["reCAPTCHAPrivateKey"].ToString(); } } protected void btnSubmit_Click(object sender, EventArgs e) { if (recaptcha.IsValid) lblResult.Text = "Correct!!!"; else lblResult.Text = "Incorrect!!!"; lblResult.Visible = true; } } |
If we need a simple captcha like Math Captcha, take a look on how to implement Math Captch with ASP.NET (C#)