2010-08-23 79 views
0

我使用MvcRecaptcha来防止在ASP.NET MVC 2.0站点上复杂的未经身份验证的客户端表单的博客帖子。使用MvcReCaptcha仅请求验证码

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

我已经使用Session["CaptchaSuccess"] = true;变量来抑制在我看来Html.GenerateCaptcha()成功进入下面的尝试,但在我的[HttpPost]鉴于[CaptchaValidator]属性的存在会导致一个错误,因为它自然需要一些reCAPTCHA的表单输入。

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

回答

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)); 
     }