2013-02-28 15 views

回答

1

一个简单的实现将存储在cookie中的值。

(CSHTML /剃刀)

<h2>@ViewBag.Captcha</h2> 
@using (Html.BeginForm("Captcha", "Home", FormMethod.Post)) 
{  
    @Microsoft.Web.Helpers.ReCaptcha.GetHtml(publicKey: "...")  
    <input type="submit" value="validate"/> 
} 

(控制器)

public ActionResult Index() 
{ 
    ViewBag.Captcha = 0; 
    return View(); 
} 


public ActionResult Captcha() 
    { 
     var valid = Microsoft.Web.Helpers.ReCaptcha.Validate(privateKey: "..."); 
     if (valid) 
     { 
      return RedirectToAction("Success"); 
     } 
     else 
     { 
      int failValue = 0; 
      var failCookie = Request.Cookies["failCount"]; 

      if (failCookie == null) 
      { 
       failValue = 1; 
       failCookie = new HttpCookie("failCount"); 
       failCookie.Value = failValue.ToString(); 
       Response.Cookies.Add(failCookie); 
      } 
      else 
      { 
       failValue = int.Parse(failCookie.Value); 
       failValue = failValue + 1; 
       failCookie.Value = failValue.ToString(); 
      } 

      ViewBag.Captcha = "Failed " + failValue + " times"; 
      return View("Index"); 
     }   
    }