【问题标题】:ASP.Net MVC Recaptcha Jquery Ajax issueASP.Net MVC Recaptcha Jquery Ajax 问题
【发布时间】:2015-02-24 08:01:34
【问题描述】:

我正在使用 ASP.Net MVC 并尝试将 Google reCaptcha 对象实现到页面中。

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

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

任何建议让它像我一样保持轻量级,但要让它继续工作。

注意:这里的大部分逻辑已经被剥离,只是试图让验证码逻辑正常工作。

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

提前致谢,

【问题讨论】:

标签: jquery html ajax asp.net-mvc recaptcha


【解决方案1】:

在疯了一个多星期后,我终于得到了一个直接使用开发者 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; }
    }

【讨论】:

    【解决方案2】:

    你的控制器方法

    public JsonResult CreateUser() //<-- CamelCase
    

    与ajax调用不匹配

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

    【讨论】:

    • 输入问题时出现拼写错误,现已编辑并修复问题。阅读问题会告诉你这不是问题。我已经进入函数内部了。
    猜你喜欢
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多