Nó rất dễ:
- Truy cập bảng điều khiển quản trị google reCaptcha của bạn
- Thêm
localhost& 127.0.0.1vào tên miền của một trang web mới như hình ảnh sau đây.

Cập nhật:
Nếu câu hỏi của bạn là làm thế nào để thiết lập reCaptchatrang web Google để sử dụng nó trong localhost, thì tôi đã được viết ở trên nhưng nếu bạn tò mò rằng làm thế nào bạn có thể sử dụng reCAPTCHAtrên cả hai localhost và website hostbởi các mã tối thiểu trong bộ điều khiển của bạn và ngăn chặn một số mã như ConfigurationManager.AppSettings["ReCaptcha:SiteKey"]trong đó Tôi giúp bạn với mô tả thêm và mã trong câu trả lời của tôi.
Bạn có thích các hành động GET và POST sau đây không?
Nó hỗ trợ reCaptcha và không cần bất kỳ mã nào khác để xử lý reCaptcha.
[HttpGet]
[Recaptcha]
public ActionResult Register()
{
// Your codes in GET action
}
[HttpPost]
[Recaptcha]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model, string reCaptcha_SecretKey){
// Your codes in POST action
if (!ModelState.IsValid || !ReCaptcha.Validate(reCaptcha_SecretKey))
{
// Your codes
}
// Your codes
}
Trong Chế độ xem: ( tham khảo )
@ReCaptcha.GetHtml(@ViewBag.publicKey)
@if (ViewBag.RecaptchaLastErrors != null)
{
<div>Oops! Invalid reCAPTCHA =(</div>
}
Để dùng nó
A) Thêm phần sau ActionFiltervào dự án Web của bạn:
public class RecaptchaAttribute : FilterAttribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
var setting_Key = filterContext.HttpContext.Request.IsLocal ? "ReCaptcha_Local" : "ReCaptcha";
filterContext.ActionParameters["ReCaptcha_SecretKey"] = ConfigurationManager.AppSettings[$"{setting_Key}:SecretKey"];
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
var setting_Key = filterContext.HttpContext.Request.IsLocal ? "ReCaptcha_Local" : "ReCaptcha";
filterContext.Controller.ViewBag.Recaptcha = ReCaptcha.GetHtml(publicKey: ConfigurationManager.AppSettings[$"{setting_Key}:SiteKey"]);
filterContext.Controller.ViewBag.publicKey = ConfigurationManager.AppSettings[$"{setting_Key}:SiteKey"];
}
}
B) Thêm các reCaptchaphím cài đặt cho cả hai localhostvà websitethích nó trong webconfigtệp của bạn :
<appSettings>
<!-- RECAPTCHA SETTING KEYS FOR LOCALHOST -->
<add key="ReCaptcha_Local:SiteKey" value="[Localhost SiteKey]" />
<add key="ReCaptcha_Local:SecretKey" value="[Localhost SecretKey]" />
<!-- RECAPTCHA SETTING KEYS FOR WEBSITE -->
<!--<add key="ReCaptcha:SiteKey" value="[Webite SiteKey]" />
<add key="ReCaptcha:SecretKey" value="[Webite SecretKey]" />-->
<!-- OTHER SETTING KEYS OF YOUR PROJECT -->
</appSettings>
Lưu ý: Bằng cách này, bạn không cần đặt reCaptcha_SecretKeytham số trong hành động đăng hoặc bất kỳ ViewBagreCaptcha nào theo cách thủ công trong Hành động và Chế độ xem của mình, tất cả chúng sẽ được điền tự động khi chạy với các giá trị phù hợp tùy thuộc vào bạn đã chạy dự án trên localhost hoặc trang web .😉