我在使用验证码发生器。
http://xcaptcha.codeplex.com/
Session.Add
用于比较验证码生成与应答。我想让这成为我的模型的规则违反检查的一部分,但我似乎找不到/与会话的正确部分有工作。我是否错过了从模型的GetRuleViolations中导航到会话的方法?还有其他建议吗
// Controller
public ActionResult Image()
{
var builder = new XCaptcha.ImageBuilder();
var result = builder.Create();
Session.Add("CaptchaKey", result.Solution);
return new FileContentResult(result.Image, result.ContentType);
}
// My model
public IEnumerable<RuleViolation> GetRuleViolations()
{
// This isn't correct... it isn't stored in server variables
string captchaAnswer = HttpContext.Current.Request.ServerVariables.Get("CaptchaKey");
// No such thing..
string res = Session["Something"].ToString();
}
// My eh solution
// Controller
[HttpPost]
public ActionResult ContactUs(EmailModel e, FormCollection collection)
{
string captchaAnswer = Session["CaptchaKey"].ToString();
string captchaText = collection["CaptchaText"].ToUpper().ToString();
bool correctCaptcha = (captchaAnswer.CompareTo(captchaText) == 0) ? true : false;
if (e.IsValid && correctCaptcha)
{
EmailHelper.SendMessage(e);
return RedirectToAction("ContactSuccess");
}
else
{
if (!correctCaptcha)
ModelState.AddModelError("Captcha", "Incorrect Captcha answer");
ModelState.AddRuleViolations(e.GetRuleViolations());
}
return View(e);
}