如何在MVC3应用程序中实现Google reCaptcha?

upd*_*dev 8 asp.net asp.net-mvc recaptcha c#-4.0 asp.net-mvc-3

任何人都可以解释如何在我的MVC3应用程序中使用像stackoverflow这样的reCaptcha功能.

你怎么能定制呢?

CD *_*ith 30

我使用Google ReCaptcha,它运行良好,实现起来非常简单.

请注意,如果您使用的是Https,请确保您拥有当前版本的dll(此时为1.0.5.0)

您需要在Google Recaptcha网站上创建一个帐户,并获取一组公钥和私钥.将密钥添加到Web项目主web.config文件中:

<appSettings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    <add key="ReCaptchaPrivateKey" value="put your private key value here" />
    <add key="ReCaptchaPublicKey" value="put your public key value here" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

现在使用NuGet并安装.NET的reCAPTCHA插件

然后,转到VIEWS文件夹中的web.config文件.添加此行:

<namespaces>
  <add namespace="System.Web.Mvc" />
  <add namespace="System.Web.Mvc.Ajax" />
  <add namespace="System.Web.Mvc.Html" />
  <add namespace="System.Web.Routing" />
  <add namespace="Recaptcha"/>
</namespaces>
Run Code Online (Sandbox Code Playgroud)

然后,在您的视图中,您要显示验证码,请在文件顶部添加using语句

@using Recaptcha;
Run Code Online (Sandbox Code Playgroud)

然后将其添加到您的视图中:

<div class="editor-label">
    Are you a human?
</div>
<div class="editor-field">
    @Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
    @Html.ValidationMessage("captcha")
</div>
Run Code Online (Sandbox Code Playgroud)

在控制器操作中,您需要修改签名以接受验证码结果:

[HttpPost]
[RecaptchaControlMvc.CaptchaValidator]
public ActionResult ForgotPassword(CheckUsernameViewModel model, bool captchaValid, string captchaErrorMessage) {
    if (!Membership.EnablePasswordReset)
        throw new Exception("Password reset is not allowed\r\n");
    if(ModelState.IsValid) {
        if(captchaValid) {
            return RedirectToAction("AnswerSecurityQuestion", new { username = model.Username });
        }
        ModelState.AddModelError("", captchaErrorMessage);
    }
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

按照这些步骤,我可以在几个页面上实现验证码,并且运行顺畅.请注意,控制器操作上的参数名称必须正确命名:

bool captchaValid, string captchaErrorMessage
Run Code Online (Sandbox Code Playgroud)

如果您更改了这些参数名称,那么当表单发回控制器操作时,您将在运行时收到错误.