2014-12-27 105 views
8

我正在使用ASP.Net MVC并尝试将Google reCaptcha对象实现为页面。ASP.Net MVC Recaptcha Jquery Ajax问题

我想避免在我的表单中使用模型,并且只想直接调用使用jquery ajax的方法。

我有验证码出现,但是在调试器中检查RecaptchaVerificationHelper对象时,输入的任何内容都显示为空。

任何建议,以保持它像我拥有它轻量级,但保持它的工作。

注意:大多数逻辑已被剥离出来,只是试图让验证码逻辑工作。

CSHTML样品:

@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服务器代码示例:

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); 
       } 
     } 

由于事先

+0

的NuGet **谷歌验证码V2 **为MVC 4和5 - [NuGet包(HTTPS://www.nuget。 org/packages/reCAPTCH.MVC /) - [Demo And Document](http://recaptchamvc.apphb.com/) – Sender

回答

7

经过一周的生气,我终于找到了一个直接使用开发者API的工作解决方案。

我所做的是使用jsAPI,并使用API​​手动添加验证码控件到页面。提交时,我捕获了recaptcha响应并将其发送给服务器端。

从服务器端,我然后验证请求遵循API说明和使用本教程在这里找到:http://www.codeproject.com/Tips/851004/How-to-Validate-Recaptcha-V-Server-side 然后我发送请求并相应地处理响应。

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; } 
    } 
1

你的控制器方法

public JsonResult CreateUser() //<-- CamelCase 

不AJAX调用匹配

url: 'createUser', //<-- small case 
+0

现在输入问题,编辑和修复问题时出现错字。阅读这个问题会告诉你这不是问题。我已经进入了这个功能。 – Cyassin