2010-08-23 53 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)); 
     }