0

我正在使用MvcRecaptcha来防止 ASP.NET MVC 2.0 站点上复杂的未经身份验证的客户端表单的机器人发布。

我只想要求未经身份验证的客户提供一个正确的 CAPTCHA 条目,即使某些表单的输入不正确。

在成功输入后,我尝试在视图中使用Session["CaptchaSuccess"] = true;变量来抑制Html.GenerateCaptcha(),但我的视图中存在该[CaptchaValidator]属性[HttpPost]会导致错误,因为它自然需要一些 ReCaptcha 表单输入。

可靠地实现这一目标的最简单方法是什么,包括在移动浏览器上?

4

1 回答 1

0

通过修改[CaptchaValidatorAttribute]OnActionExecuting 方法解决,其中CaptchaSuccessFieldKey指的是常量字符串值“CaptchaSuccess”:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
            bool? bCaptchaSuccess = filterContext.HttpContext.Session[CaptchaSuccessFieldKey] as bool?;
            if (bCaptchaSuccess.HasValue && bCaptchaSuccess.Value)
            {
                filterContext.ActionParameters["captchaValid"] = true;
            }
            else
            {

                var captchaChallengeValue = filterContext.HttpContext.Request.Form[ChallengeFieldKey];
                var captchaResponseValue = filterContext.HttpContext.Request.Form[ResponseFieldKey];
                var captchaValidtor = new Recaptcha.RecaptchaValidator
                                          {
                                              PrivateKey = ConfigurationManager.AppSettings["ReCaptchaPrivateKey"],
                                              RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
                                              Challenge = captchaChallengeValue,
                                              Response = captchaResponseValue
                                          };

                var recaptchaResponse = captchaValidtor.Validate();

                // this will push the result value into a parameter in our Action
                filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid;
            }

            base.OnActionExecuting(filterContext);

            // Add string to Trace for testing
            //filterContext.HttpContext.Trace.Write("Log: OnActionExecuting", String.Format("Calling {0}", filterContext.ActionDescriptor.ActionName));
        }
于 2010-08-23T22:45:37.777 回答