MrMistreater

Using Recaptcha in an MVC3 / Razor application

May 7th, 2012
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.20 KB | None | 0 0
  1. // First, install the reCaptcha library from Nuget https://nuget.org/packages/recaptcha.
  2. // Then, create your public and private keys at http://www.google.com/recaptcha.
  3.  
  4. // 1. Create an extension method to genereate the Recaptcha javascript
  5. public static class Extension
  6. {
  7.     public static MvcHtmlString GenerateCaptcha(this HtmlHelper htmlHelper)
  8.     {
  9.         var html = Recaptcha.RecaptchaControlMvc.GenerateCaptcha(htmlHelper);
  10.         return MvcHtmlString.Create(html);
  11.     }
  12. }
  13.  
  14. // 2. In the controller, add the CaptchaValidatorAttribute attribute and the captchaValid and captchaErrorMessage parameters to the method
  15. [HttpPost]
  16. [Recaptcha.RecaptchaControlMvc.CaptchaValidatorAttribute]
  17. public ActionResult PostMessage(Message message, bool captchaValid, string captchaErrorMessage)
  18. {
  19.     if(captchaValid)
  20.     {
  21.         /// ... do something ... ///
  22.     }
  23. }
  24.  
  25. // 3. In the Global.asax's Application_Start method, assign you public and private keys
  26. protected void Application_Start()
  27. {
  28.     Recaptcha.RecaptchaControlMvc.PublicKey = "0123456789";
  29.     Recaptcha.RecaptchaControlMvc.PrivateKey = "9876543210";
  30. }
  31.  
  32. // 4. In the view, add the following to generate the Recaptcha content
  33. <tr>
  34.     <td></td>
  35.     <td>@Html.GenerateCaptcha()</td>
  36. </tr>
Advertisement
Add Comment
Please, Sign In to add comment