2014-12-27 159 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