【问题标题】:Asking for CAPTCHA only once with MvcReCaptcha使用 Mvc ReCaptcha 仅询问一次 CAPTCHA
【发布时间】:2011-04-02 20:44:38
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: asp.net-mvc spam-prevention recaptcha


    【解决方案1】:

    通过修改[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));
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 2015-11-18
      • 2023-01-20
      • 2015-03-02
      • 1970-01-01
      相关资源
      最近更新 更多