Search code examples
c#asp.net-mvcrecaptcha

Using reCAPTCHA with ASP.NET MVC


I've used reCAPTCHA many times in my WebForms applications. Now I'd like to add it to an ASP.NET MVC application.

I found what appears to be some good code in RecaptchaControlMvc but, incredibly, I haven't been able to find a single paragraph or example on how to use this control.

I've posted in the Google reCAPTCHA group but it's dead.

Can anyone point me to an example that uses this control, a paragraph about how to use it, or suggest an alternative?

Note: I know there are similar questions on stackoverflow, but none that I've found discuss how to use this control.


Solution

  • Some code here

    You add the attribute like this:

    [CaptchaValidator]  
    [AcceptVerbs( HttpVerbs.Post )]  
    public ActionResult SubmitForm( Int32 id, bool captchaValid )  
    {  
    .. Do something here  
    }  
    

    You render the captcha in your view:

    <%= Html.GenerateCaptcha() %> 
    

    which is something like this:

    public static string GenerateCaptcha( this HtmlHelper helper )  
    {           
        var captchaControl = new Recaptcha.RecaptchaControl  
                {  
                        ID = "recaptcha",  
                        Theme = "blackglass",  
                    PublicKey = -- Put Public Key Here --,  
                            PrivateKey = -- Put Private Key Here --  
                };  
    
        var htmlWriter = new HtmlTextWriter( new StringWriter() );  
        captchaControl.RenderControl(htmlWriter);  
        return htmlWriter.InnerWriter.ToString();  
    }