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

标签 c# asp.net asp.net-mvc asp.net-mvc-4

我是 MVC 的新手。我已将 reCAPTCHA 添加到测试网站并且它可以正常工作,但我需要检查用户是否已选中该复选框。然后我希望在 @html.ValidationSummary 列表中显示失败,以保持网站上的所有内容干净,而不是通过 ViewBag 添加单独的消息。

请注意,我创建了一个 MVC 项目模板,因此很多代码已经由 VS2013 生成。因此,我需要将其与网站整合。此外,Microsoft 的一个示例显示了如何在 Controller 中执行此操作,尽管他们建议您不要在 Controller 中执行此操作,因为 Controller 应仅包含与应用程序流控制相关的逻辑——Microsoft 只是采取了一条捷径来简化操作( SMH)。

https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/performing-simple-validation-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);
    }

注册.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")
}

最佳答案

当验证码验证失败时,只需在 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)
{

..........

验证摘要中会显示“输入的验证码无效”

关于c# - 如何将 reCAPTCHA 验证失败添加到 @html.ValidationSummary 列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42159499/

相关文章:

c# - 使用 C# 替换索引图像中的颜色

c# - 当它的一些参数是委托(delegate)时,是否可以在 C# 中使用 "C++ Library Function"?

.net - 可空枚举类型的奇怪行为

c# - 通过 Windows Phone 访问 WCF 服务

c# - 如何在 MVC.net 网页中保留由 @Html.ListBoxFor 做出的选择中的所有值?

c# - MVC3 中的 CSS 背景图像——续

C# WinForms - 在同一个 TreeViewControl 中拖放

c# - Web Api .net 框架 4.6.1 和 identityServer4

c# - 主题 + 动态控件创建 + 不可见的 UserControl = View 状态错误?

asp.net-mvc - Identity 2.0 使用 token 重置短信密码