public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!GoogleCaptchaConfiguration.EnableInDebuggingMode) { if (HttpContext.Current.IsDebuggingEnabled) { return; } } var response = GetResponseKey(filterContext, "g-recaptcha-response"); var client = new GoogleCaptchaClient(); var secretkey = GoogleCaptchaConfiguration.Secretkey ?? CaptchException.ThrowSecretkeyNotInitilized(); var validationKey = GoogleCaptchaConfiguration.ValidationInputName; var validationMessage = GoogleCaptchaConfiguration.ValidationMessage; if (!client.IsAcceptAsync(response, secretkey).GetAwaiter().GetResult()) { filterContext.Controller.ViewData.ModelState.AddModelError(validationKey, validationMessage); filterContext.Result = new ViewResult { ViewName = filterContext.ActionDescriptor.ActionName, ViewData = filterContext.Controller.ViewData, TempData = filterContext.Controller.TempData }; } base.OnActionExecuting(filterContext); }
public static MvcHtmlString RenderCaptcha(this HtmlHelper helper, string sitekey = null) { var validationInputName = GoogleCaptchaConfiguration.ValidationInputName; var captchaTag = new TagBuilder("div"); var htmlString = new StringBuilder(); var hiddenInput = helper.Hidden(validationInputName); if (helper.ViewData.ModelState[validationInputName] != null && helper.ViewData.ModelState[validationInputName].Errors.Any()) { var validationInput = helper.ValidationMessage(validationInputName); htmlString.AppendLine(validationInput.ToHtmlString()); } captchaTag.Attributes.Add("class", "g-recaptcha"); captchaTag.Attributes.Add("data-sitekey", sitekey ?? GoogleCaptchaConfiguration.Sitekey ?? CaptchException.ThrowSiteKeyNotInitialized()); captchaTag.Attributes.Add("data-theme", GoogleCaptchaConfiguration.Theme.ToString().ToLower()); captchaTag.Attributes.Add("data-callback", GoogleCaptchaConfiguration.ResponseCallback); htmlString.AppendLine(captchaTag.ToString()); htmlString.AppendLine(hiddenInput.ToHtmlString()); return(MvcHtmlString.Create(htmlString.ToString())); }