简体   繁体   English

如何将reCAPTCHA验证失败添加到@html.ValidationSummary列表中

[英]How do I add reCAPTCHA validation failure into the @html.ValidationSummary list

I am new to MVC. 我是MVC的新手。 I have added reCAPTCHA to a test website and it works, but I need to include a check for whether or not the user has selected the checkbox. 我已经将reCAPTCHA添加到测试网站并且它可以工作,但是我需要检查用户是否选中了复选框。 I then want a failure to display in the @html.ValidationSummary list so as to keep everything clean on the website, as opposed to adding a separate message via a ViewBag. 然后我想要在@html.ValidationSummary列表中显示失败,以便在网站上保持一切清洁,而不是通过ViewBag添加单独的消息。

Please note that I created an MVC project template, so a lot of code has already been generated by VS2013. 请注意,我创建了一个MVC项目模板,因此VS2013已经生成了很多代码。 Thus, I need to integrate this in with the website. 因此,我需要将其与网站整合。 Also, one of Microsoft's example shows how to do it in the controller, even though they recommend that you not do it in the controller because a controller should contain only logic related to application flow control - Microsoft just took a shortcut to keep things simple (SMH). 此外,Microsoft的一个示例显示了如何在控制器中执行此操作,即使他们建议您不要在控制器中执行此操作,因为控制器应该只包含与应用程序流控制相关的逻辑 - Microsoft只是采用了一种快捷方式来保持简单( SMH)。

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/performing-simple-validation-cs https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/performing-simple-validation-cs

AccountController.cs AccountController.cs

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        //Validate Google reCAPTCHA here
        var response = Request["g-recaptcha-response"];
        string secretKey = "SITE SECRET";
        var client = new WebClient();
        var recaptchaResult = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
        var obj = JObject.Parse(recaptchaResult);
        var status = (bool)obj.SelectToken("success");
        //ViewBag.Message = status ? "Google reCaptcha validation success" : "Google reCaptcha validation failed";

        if (ModelState.IsValid && status)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

Register.cshtml Register.cshtml

@model WebApp1.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{  
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <div class="g-recaptcha" data-sitekey="SITE SECRET"></div>
            <br />
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

@section Scripts {
    <script type="text/javascript" src='https://www.google.com/recaptcha/api.js' async></script>
    @Scripts.Render("~/bundles/jqueryval")
}

Just add an error on the ModelState when the captcha validation fails : 只需在验证码验证失败时在ModelState上添加错误:

....
var status = (bool)obj.SelectToken("success");

if (!status)
   ModelState.AddModelError("", "Captcha entered is not valid"); 
   // This will make automatically ModelState.IsValid to false

if (ModelState.IsValid)
{

..........

"Captcha entered is not valid" will be displayed in the validation summary “输入的验证码无效”将显示在验证摘要中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM