Created
June 4, 2012 13:31
-
-
Save Dynyx/2868399 to your computer and use it in GitHub Desktop.
Using ReCaptcha in an MVC application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// First, install the reCaptcha library from Nuget https://nuget.org/packages/recaptcha. | |
// Then, create your public and private keys at http://www.google.com/recaptcha. | |
// 1. Create an extension method to genereate the Recaptcha javascript | |
public static class Extension | |
{ | |
public static MvcHtmlString GenerateCaptcha(this HtmlHelper htmlHelper) | |
{ | |
var html = Recaptcha.RecaptchaControlMvc.GenerateCaptcha(htmlHelper); | |
return MvcHtmlString.Create(html); | |
} | |
} | |
// 2. In the controller, add the CaptchaValidatorAttribute attribute and the captchaValid and captchaErrorMessage parameters to the method | |
[HttpPost] | |
[Recaptcha.RecaptchaControlMvc.CaptchaValidatorAttribute] | |
public ActionResult PostMessage(Message message, bool captchaValid, string captchaErrorMessage) | |
{ | |
if(captchaValid) | |
{ | |
/// ... do something ... /// | |
} | |
} | |
// 3. In the Global.asax's Application_Start method, assign you public and private keys | |
protected void Application_Start() | |
{ | |
Recaptcha.RecaptchaControlMvc.PublicKey = "0123456789"; | |
Recaptcha.RecaptchaControlMvc.PrivateKey = "9876543210"; | |
} | |
// 4. In the view, add the following to generate the Recaptcha content | |
<tr> | |
<td></td> | |
<td>@Html.GenerateCaptcha()</td> | |
</tr> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment