It's so easy:
localhost
& 127.0.0.1
to domains of a new site like the following image.Update:
If your question is how to set reCaptcha
in Google site for using it in localhost, then i has been wrote it above but if you are curious that how you can using reCAPTCHA
on both localhost
and website host
by minimal codes in your controller and prevent some codes like ConfigurationManager.AppSettings["ReCaptcha:SiteKey"]
in it then I help you with this extra description and codes in my answer.
Do you like the following GET and POST actions?
It support reCaptcha and doesn't need any other codes for handling 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 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
& website
like it 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
reCaptcha_SecretKey
parameter in the post action or anyViewBag
for reCaptcha manually in your Actions and Views, all of them will be filled automatically at runtime with appropriate values depending on you have run the project on the localhost or website.