理解C#生成验证码的过程

2019-12-30 11:56:51王旭

验证码页面Action:


public ActionResult VerifyCode()
{
  string code;
  Bitmap bmp = VerifyCodeHelper.CreateVerifyCodeBmp(out code);
  Bitmap newbmp = new Bitmap(bmp, 108, 36);
  HttpContext.Session["VerifyCode"] = code;

  Response.Clear();
  Response.ContentType = "image/bmp";
  newbmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Bmp);

  return View();
}

说明:前台页面为空的cshtml页面,验证码的值放在Session中。

使用验证码的页面:

显示验证码的img:

<img id="verifyCode" src="" style="margin: 0px; padding: 0px; line-height: 25.2px; width: 660px; overflow: hidden; clear: both;">


$(function () {
  //刷新验证码
  $("#refreshVerifyCode").click(function () {
    refreshVerifyCode(); //刷新验证码
  });
  $("#verifyCode").click(function () {
    refreshVerifyCode(); //刷新验证码
  });
  refreshVerifyCode();
});

刷新验证码:


//刷新验证码
function refreshVerifyCode() {
  $("#verifyCode").attr("src", "VerifyCode?t=" + new Date().valueOf());
}
 

判断用户输入的文本是否与验证码相同的Action:


public ActionResult CheckVCode(string vcode)
{
  if (HttpContext.Session["VerifyCode"].ToString().ToLower() == vcode.ToLower())
  {
    Dictionary<string, object> dic = new Dictionary<string, object>();
    dic["ok"] = true;
    return Content(JsonConvert.SerializeObject(dic));
  }
  else
  {
    Dictionary<string, object> dic = new Dictionary<string, object>();
    dic["ok"] = false;
    return Content(JsonConvert.SerializeObject(dic));
  }
}

以上就是本文的全部内容,希望对大家学习C#生成验证码的方法有所帮助。