Asp.net

如何在 MVC3 應用程序中實現 Google reCaptcha?

  • December 19, 2012

誰能解釋如何在我的 MVC3 應用程序中擁有像 stackoverflow 這樣的 reCaptcha 功能。

你怎麼能定制呢?

我使用 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>

現在使用 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>

然後,在您想要顯示驗證碼的視圖中,在文件頂部添加 using 語句

@using Recaptcha;

然後將其添加到您的視圖中:

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

在您的控制器操作中,您需要修改簽名以接受驗證碼結果:

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

按照這些步驟,我可以在多個頁面上實現驗證碼,並且執行順利。請注意,控制器操作上的參數名稱必須正確命名:

bool captchaValid, string captchaErrorMessage

如果您更改了這些參數名稱,當您的表單回傳到控制器操作時,您將在執行時收到錯誤消息。

引用自:https://stackoverflow.com/questions/9740402