如何使用MvcCaptcha验证码控件

  1. 下载并在ASP.NET MVC项目中添加对MvcCaptcha.dll的引用;
  2. 在当前页面的Form中添加验证码输入文本框,供用户手工输入验证码用,验证码文本框可以放在Form中的任何地方,示例如下:
    <input type="text" name="_mvcCaptchaText" id="_mvcCaptchaText" />
    文本框的name和id可以是MvcCaptcha默认的“_mvcCaptchaText”,也可以是自定义的其它值,在当前Form被提交后,MvcCaptcha控件会在服务器端获取这个文本框的值进行验证,如果文本框的name和id值不是默认的“_mvcCaptchaText”,则在在前台注册码证码控件和在后台进行验证时需要进行额外设置,下面会详细说明。
  3. 在当前页面上添加放置验证码图片的容器元素,可以是div、span等任何元素,并为其设置id值,示例如下:
    <div id="captchaImage"></div>
    id属性值可以默认为“captchaImage”,如果设置为其它值,则需要在注册MvcCaptcha控件时额外设置,下面会有详细说明。
  4. 在Form内注册MvcCaptcha,示例如下:

    Razor语法:

    @Html.MvcCaptcha()

    WebForm语法:

    <%:Html.MvcCaptcha()%>
    若前面所讲的验证码输入文本框的id不是默认的“_mvcCaptchaText”,或者验证码图片容器元素的id不是默认的“captchaImage”,则需要在MvcCaptchaOptions属性中指定,假定验证码文本框的id是“captchaInput”,图片验证码的容器元素的id是“imgContainer”,则上面的注册代码应改为:

    Razor语法:

    @Html.MvcCaptcha(new MvcCaptchaOptions {ValidationInputBoxId = "captchaInput", CaptchaImageContainerId = "imgContainer" })

    WebForm语法:

    <%:Html.MvcCaptcha(new MvcCaptchaOptions {ValidationInputBoxId = "captchaInput", CaptchaImageContainerId = "imgContainer" })%>
    其中的ValidationInputBoxId是验证码输入文本框的客户端ID,CaptchaImageContainerId是包含验证码图片的容器元素的客户端ID。

    若要启用Ajax延迟加载验证码图片功能,则需要设置MvcCaptchaOptions属性的DelayLoad为true,示例如下:

    Razor语法:

    @Html.MvcCaptcha(new MvcCaptchaOptions {DelayLoad = true,ValidationInputBoxId = "captchaInput", CaptchaImageContainerId = "imgContainer" })

    WebForm语法:

    <%:Html.MvcCaptcha(new MvcCaptchaOptions {DelayLoad = true,ValidationInputBoxId = "captchaInput", CaptchaImageContainerId = "imgContainer" })%>
  5. 在后台Controller的Action方法上添加ValidateMvcCaptchaAttribute过滤器,示例如下:
    [ValidateMvcCaptcha][HttpPost]
    public ActionResult Login(LoginModel login){...}
    
    如果前面提到的验证码输入文本框的name属性值不是默认的“_mvcCaptchaText”时,需要在过滤器中显式指定该值,假定验证码文本框的name属性值为“captchaInput”,则代码应改为:
    [ValidateMvcCaptcha("captchaInput")][HttpPost]
    public ActionResult Login(LoginModel login){...}
    
    在Action方法中,用ModelState.IsValid进行验证,示例如下:
    [ValidateMvcCaptcha("captchaInput")][HttpPost]
    public ActionResult Login(LoginModel login){
    if (ModelState.IsValid){
    //验证通过
    }
    else{
    //验证失败
    }}
小技窍:
若要进行客户端unobtrusive Javascript验证,可以在验证码文本框代码中加上 data-val="true" data-val-required="验证码不能为空",示例如下:
<input type="text" name="_mvcCaptchaText" id="_mvcCaptchaText" data-val="true" data-val-required="验证码不能为空" />