It's so easy:
- Go to your google reCAPTCHA adminstration panel
- Add
localhost
& 127.0.0.1
to the domains of a new site, like the following image.

Update:
If your question is how to set reCAPTCHA on the Google site for using it in localhost, then it has be as I wrote it above, but if you are curious how you can use reCAPTCHA on both localhost
and a website host
by minimal code in your controller and prevent some codes like ConfigurationManager.AppSettings["ReCaptcha:SiteKey"]
in it, then I help you with this extra description and code in my answer.
Do you like the following GET and POST actions?
The code below supports reCAPTCHA and doesn't need any other code for handling reCAPTCHA.
[HttpGet]
[Recaptcha]
public ActionResult Register()
{
// Your code in the GET action
}
[HttpPost]
[Recaptcha]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model, string reCaptcha_SecretKey){
// Your code in the POST action
if (!ModelState.IsValid || !ReCaptcha.Validate(reCaptcha_SecretKey))
{
// Your code
}
// Your code
}
In View: (reference)
@ReCaptcha.GetHtml(@ViewBag.publicKey)
@if (ViewBag.RecaptchaLastErrors != null)
{
<div>Oops! Invalid reCAPTCHA =(</div>
}
To use it
A) Add the following ActionFilter
to your Web project:
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) Add the reCAPTCHA settings keys for both localhost
and website
like this in your webconfig
file:
<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>
Note: By this way you did not need set the reCaptcha_SecretKey
parameter in the post action or any ViewBag
for reCaptcha manually in your Actions and Views. All of them will be filled in automatically at runtime with appropriate values depending on if you have run the project on the localhost or website.