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.
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();
}
I can provide you an easy alternative method to use google recaptcha.
Here you can find the complete reference about Google new reCAPTCHA using asp.net mvc
First all of you need to Sign up & Generate Google reCAPTCHA API.
Go to http://www.google.com/recaptcha then click on the top right corner Get reCAPTCHA button
Second, Write html code in your view. Here replace text "Your sitekey here"
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
@using (Html.BeginForm("FormSubmit", "Home", FormMethod.Post))
{
<div class="g-recaptcha" data-sitekey="Your sitekey here"></div>
<input type="submit" value="Submit" />
}
</div>
<span style="display:inline-block; font-size:20px;margin:20px 0;padding:20px;border:1px solid #D3D3D3">
@ViewBag.Message
</span>
<script src='https://www.google.com/recaptcha/api.js' type="text/javascript"></script>
3rd and last, Write action code for validate google reCaptcha
[HttpPost]
public ActionResult FormSubmit()
{
//Validate Google recaptcha here
var response = Request["g-recaptcha-response"];
string secretKey = "Your secret here";
var client = new WebClient();
var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
var obj = JObject.Parse(result);
var status = (bool)obj.SelectToken("success");
ViewBag.Message = status ? "Google reCaptcha validation success" : "Google reCaptcha validation failed";
//When you will post form for save data, you should check both the model validation and google recaptcha validation
//EX.
/* if (ModelState.IsValid && status)
{
}*/
//Here I am returning to Index page for demo perpose, you can use your view here
return View("Index");
}