我正在使用MvcRecaptcha来阻止ASP.NET MVC 2.0站点上复杂的未经身份验证的客户端表单的机器人帖子。
我只想从未经身份验证的客户端请求一个正确的CAPTCHA条目,即使某些表单的输入不正确。
我尝试在成功输入后使用Session["CaptchaSuccess"] = true;
变量在我的视图中取消Html.GenerateCaptcha()
,但[CaptchaValidator]
视图中存在[HttpPost]
属性会导致错误,因为它自然需要一些ReCaptcha表单输入。
实现这一目标的最简单方法是什么,包括移动浏览器?
答案 0 :(得分: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));
}