如果我们可以实施,如何验证用户响应?
这是我的代码
<script type="text/javascript" src="https://www.google.com/recaptcha/api/challenge?k=<Public Key>"></script>
<noscript>
<iframe src="https://www.google.com/recaptcha/api/noscript?k=<Public Key>" height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge">
</noscript>
答案 0 :(得分:0)
你可以有一个类,如
public class GoogleReCaptcha
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("error-codes")]
public List<string> ErrorCodes { get; set; }
}
以及controller
调用的服务类中的方法,例如:
public bool ValidateReCaptcha(ModelStateDictionary modelState)
{
var response = HttpContext.Current.Request["g-recaptcha-response"];
var client = new WebClient();
var reply =
client.DownloadString(
string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", ApplicationManager.GoogleRecaptchaSecret, response));
var captchaResponse = JsonConvert.DeserializeObject<GoogleReCaptcha>(reply);
if (!captchaResponse.Success)
{
if (captchaResponse.ErrorCodes.Count <= 0)
throw new Exception("Re-Captcha Returned False for Success Without any Error Codes");
switch (captchaResponse.ErrorCodes[0].ToLower())
{
case ("missing-input-secret"):
throw new Exception("Re-Captcha Secret Parameter is Missing");
case ("invalid-input-secret"):
throw new Exception("Re-Captcha Secret Parameter is Invalid or Malformed");
case ("missing-input-response"):
modelState.AddModelError("", "Capthca error, retry!.");
break;
case ("invalid-input-response"):
modelState.AddModelError("", "Captcha error, retry!");
break;
default:
modelState.AddModelError("", "Captcha error, retry!");
break;
}
return false;
}
return true;
}
您可以在POST
控制器操作中调用您的方法,例如:
if (!SomeService.ValidateReCaptcha(ModelState))
return View(model);