È così facile:
- Vai al tuo pannello di amministrazione di Google reCaptcha
- Aggiungi
localhoste 127.0.0.1ai domini di un nuovo sito come la seguente immagine.

Aggiornare:
Se la tua domanda è come impostare reCaptchanel sito di Google per usarlo in localhost, allora sono stato scritto sopra, ma se sei curioso di sapere come è possibile utilizzare reCAPTCHAsu entrambi localhost e website hostcon codici minimi nel controller e prevenire alcuni codici comeConfigurationManager.AppSettings["ReCaptcha:SiteKey"] in esso, allora Ti aiuto con questa descrizione e codici aggiuntivi nella mia risposta.
Ti piacciono le seguenti azioni GET e POST?
Supporta reCaptcha e non necessita di altri codici per la gestione di 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
}
In vista: ( riferimento )
@ReCaptcha.GetHtml(@ViewBag.publicKey)
@if (ViewBag.RecaptchaLastErrors != null)
{
<div>Oops! Invalid reCAPTCHA =(</div>
}
Per usarlo
A) Aggiungi quanto segue ActionFilteral tuo progetto Web:
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) Aggiungi le reCaptchachiavi delle impostazioni per entrambi localhoste websitecome nel tuo webconfigfile:
<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>
Nota: in questo modo non è stato necessario impostare il reCaptcha_SecretKeyparametro nell'azione post o alcuno ViewBagper reCaptcha manualmente nelle azioni e nelle viste, tutti verranno riempiti automaticamente in fase di esecuzione con valori appropriati a seconda che sia stato eseguito il progetto sull'host locale o sul sito Web .😉