2014-12-27 25 views
8

Sto utilizzando ASP.Net MVC e sto tentando di implementare un oggetto Google reCaptcha in una pagina.ASP.Net MVC Recaptcha Jquery Problema Ajax

Sto cercando di evitare l'uso di modelli nelle mie forme e voglio chiamare direttamente un metodo usando jquery ajax.

Ho il captcha da visualizzare, ma qualunque cosa entri appare come null quando si ispeziona l'oggetto RecaptchaVerificationHelper nel debugger.

Qualsiasi suggerimento per mantenerlo leggero come l'ho, ma farlo funzionare.

Nota: la maggior parte della logica è stata rimossa qui, solo cercando di far funzionare la logica captcha.

CSHTML Esempio:

@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 codice del server di esempio:

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

Grazie in anticipo,

+0

NuGet ** Google reCAPTCHA V2 ** per MVC 4 e 5 - [NuGet Package] (https: //www.nuget. org/packages/reCAPTCH.MVC /) - [Demo e documento] (http://recaptchamvc.apphb.com/) – Sender

risposta

7

Dopo essere impazzito per oltre una settimana, ho finalmente ottenuto una soluzione funzionante utilizzando direttamente l'API degli sviluppatori.

Quello che ho fatto è stato utilizzare il jsAPI e aggiungere manualmente il controllo captcha utilizzando l'API alla pagina. Al momento dell'invio, ho catturato la risposta del recaptcha e l'ho inviata dal lato server.

Dal lato server ho quindi convalidato la richiesta seguendo le istruzioni API e utilizzando questo tutorial trovato qui: http://www.codeproject.com/Tips/851004/How-to-Validate-Recaptcha-V-Server-side Ho quindi inviato la richiesta e gestito la risposta di conseguenza.

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

Il controller Metodo

public JsonResult CreateUser() //<-- CamelCase 

non corrisponde chiamata AJAX

+0

Errore durante l'immissione della domanda, modificata e corretta in questione ora. Leggendo la domanda ti dirò che questo non è il problema. Sto già entrando nella funzione. – Cyassin