I am using ASP.Net MVC to and trying to implement a Google reCaptcha object into a page.
I am trying to avoid the use of models in my forms, and want to just directly call a method using jquery ajax.
I have got the captcha to appear, but whatever I enter appears as null when inspecting the RecaptchaVerificationHelper object in debugger.
Any suggestions to keep it lightweight like I have it, but keep it working.
Note: Most of the logic has been stripped out here, just trying to get the captcha logic working.
CSHTML Sample:
@using Recaptcha.Web.Mvc;
<script type="text/javascript">
function createUser() {
$.ajax({
type: "POST",
url: 'CreateUser',
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.Success == true) {
alert("success");
//redirectSuccess();
} else {
alert("failed");
}
},
error: function (err) {
commonError(err);
}
});
}
</script>
@Html.Recaptcha(publicKey: "6LdxcPgSAA...", theme: Recaptcha.Web.RecaptchaTheme.Clean);
<br />
<input type="button" value="Submit" onclick="createUser();" style="margin-right:300px;" />
CS Server Code Sample:
public ActionResult User()
{
return View();
}
public JsonResult CreateUser()
{
Wrapper.ValidationResponse response = new Wrapper.ValidationResponse();
response.Success = true;
RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
response.Success = false;
}
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
response.Success = false;
}
try
{
//removed logic
return Json(response);
}
catch (Exception ex)
{
response.Success = false;
response.Message = "Failed to create new user. Please contact us if the issue persists.";
return Json(response);
}
}
Thanks in Advance,
After going mad for over a week, I finally got a working solution directly using the developers API.
What I did was use the jsAPI and manually add the captcha control using the API to the page. On submit, I captured the recaptcha response and sent it server side.
From server side I then validated the request following the API Instructions and using this tutorial found here: http://www.codeproject.com/Tips/851004/How-to-Validate-Recaptcha-V-Server-side I then sent the request and handled the response accordingly.
HTML:
<script type="text/javascript"
src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
var captcharesponse = grecaptcha.getResponse();
$.ajax({
type: "POST",
url: 'CreateUser',
data: "{captcharesponse:" + JSON.stringify(captcharesponse) + "}",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.Success == true) {
alert("success");
} else {
alert("failed");
}
},
error: function (err) {
commonError(err);
}
});
}
</script>
<div class="g-recaptcha"
data-sitekey="[public key here]"></div>
<br />
<input type="button" value="Submit" onclick="createUser();" style="margin-right:300px;" />
CS:
[HttpPost]
public JsonResult CreateUser(string captcharesponse)
{
Wrapper.ValidationResponse response = new Wrapper.ValidationResponse();
response.Success = true;
if (Recaptcha.Validate.Check(captcharesponse) == false)
{
response.Success = false;
}
try
{
//removed logic
return Json(response);
}
catch (Exception ex)
{
response.Success = false;
response.Message = "Failed to create new user. Please contact us if the issue persists.";
return Json(response);
}
}
public class Validate
{
public static bool Check(string response)
{
//string Response = HttpContext.Current.Request.QueryString["g-recaptcha-response"];//Getting Response String Append to Post Method
bool Valid = false;
//Request to Google Server
HttpWebRequest req = (HttpWebRequest)WebRequest.Create
(" https://www.google.com/recaptcha/api/siteverify?secret=" + WebConfigurationManager.AppSettings["recaptchaPrivateKey"] + "&response=" + response);
try
{
//Google recaptcha Response
using (WebResponse wResponse = req.GetResponse())
{
using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
{
string jsonResponse = readStream.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
MyObject data = js.Deserialize<MyObject>(jsonResponse);// Deserialize Json
Valid = Convert.ToBoolean(data.success);
}
}
return Valid;
}
catch (WebException ex)
{
throw ex;
}
}
}
public class MyObject
{
public string success { get; set; }
}
Your controller Method
public JsonResult CreateUser() //<-- CamelCase
does not match with ajax call
url: 'createUser', //<-- small case
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With