使用说明
支持WebForm以及Asp.Net Mvc构建验证码
项目源码:MasterChief.DotNet.Infrastructure.VerifyCode
Nuget:Install-Package MasterChief.DotNet.Infrastructure.VerifyCode
欢迎Star,欢迎Issues;
如何使用#
-
自定义验证码样式,只需要实现ValidateCodeType抽象类即可
/// <summary> /// 图片验证码抽象类 /// </summary> public abstract class ValidateCodeType { /// <summary> /// 创建验证码抽象方法 /// </summary> /// <param name="validataCode">验证code</param> /// <returns>Byte数组</returns> public abstract byte[] CreateImage(out string validataCode); /// <summary> /// 验证码类型名称 /// </summary> public abstract string Name { get; } /// <summary> /// 验证码Tooltip /// </summary> public virtual string Tip => "请输入图片中的字符"; /// <summary> /// 类型名称 /// </summary> public string Type => GetType().Name; }
-
在WebForm使用说明
-
新建一般处理程序
/// <summary> /// WebFormVerifyCodeHandler 的摘要说明 /// </summary> public class WebFormVerifyCodeHandler : VerifyCodeHandler, IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { var validateType = context.Request.Params["style"]; var buffer = CreateValidateCode(validateType); context.Response.ClearContent(); context.Response.ContentType = MimeTypes.ImageGif; context.Response.BinaryWrite(buffer); } public bool IsReusable => false; public override void OnValidateCodeCreated(HttpContext context, string validateCode) { context.Session["validateCode"] = validateCode; } public override byte[] CreateValidateCode(string style) { style = style?.Trim(); ValidateCodeType createCode; switch (style) { case "type1": createCode = new ValidateCode_Style1(); break; default: createCode = new ValidateCode_Style1(); break; } var buffer = createCode.CreateImage(out var validateCode); OnValidateCodeCreated(HttpContext.Current, validateCode); return buffer; } }
-
前端页面调用
<body> <form runat="server"> <div class="row"> <div class="col-md-8"> <section id="loginForm"> <div class="form-horizontal"> <h4>Use a local account to log in.</h4> <hr /> <asp:PlaceHolder runat="server" ID="ErrorMessage" Visible="false"> <p class="text-danger"> <asp:Literal runat="server" ID="FailureText" /> </p> </asp:PlaceHolder> <div class="form-group"> <asp:Label runat="server" AssociatedControlID="Email" CssClass="col-md-2 control-label">Email</asp:Label> <div class="col-md-10"> <asp:TextBox runat="server" ID="Email" CssClass="form-control" TextMode="Email" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="Email" CssClass="text-danger" ErrorMessage="The email field is required." /> </div> </div> <div class="form-group"> <asp:Label runat="server" AssociatedControlID="Password" CssClass="col-md-2 control-label">Password</asp:Label> <div class="col-md-10"> <asp:TextBox runat="server" ID="Password" TextMode="Password" CssClass="form-control" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="Password" CssClass="text-danger" ErrorMessage="The password field is required." /> </div> </div> <div class="form-group"> <%-- <asp:Image ID="Image1" runat="server" CssClass="col-md-2 control-label" ImageUrl="BackHandler/WebFormVerifyCodeHandler.ashx" />--%> <img alt="看不清,换一张" class="col-md-2 control-label" src="BackHandler/WebFormVerifyCodeHandler.ashx" onclick="this.src = 'BackHandler/WebFormVerifyCodeHandler.ashx?style=type1&ver=' + Math.random()" /> <div class="col-md-10"> <asp:TextBox runat="server" ID="VerifyCode" CssClass="form-control" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="VerifyCode" CssClass="text-danger" ErrorMessage="The VerifyCode field is required." /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <div class="checkbox"> <asp:CheckBox runat="server" ID="RememberMe" /> <asp:Label runat="server" AssociatedControlID="RememberMe">Remember me?</asp:Label> </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <asp:Button runat="server" Text="Log in" CssClass="btn btn-default" OnClick="Login_Click" /> </div> </div> </div> <p> <asp:HyperLink runat="server" ID="RegisterHyperLink" ViewStateMode="Disabled">Register as a new user</asp:HyperLink> </p> <p> <%-- Enable this once you have account confirmation enabled for password reset functionality --%> <asp:HyperLink runat="server" ID="ForgotPasswordHyperLink" ViewStateMode="Disabled">Forgot your password?</asp:HyperLink> </p> </section> </div> <div class="col-md-4"> </div> </div> </form> </body>
-
后端页面使用
protected void Login_Click(object sender, EventArgs e) { if (IsValid) { var verifyCode = VerifyCode.Text.Trim(); if (string.Compare(Session["validateCode"].ToString(), verifyCode, StringComparison.OrdinalIgnoreCase) != 0) { FailureText.Text = "验证码验证不通过."; ErrorMessage.Visible = true; } else { Response.Redirect("Default.aspx"); } } }
-
运行效果
-
-
在Asp.Net Mvc使用说明
-
新建MvcVerifyCodeHandler,并实现抽象类VerifyCodeHandler
/// <summary> /// 处理生成Mvc 程序验证码 /// </summary> public sealed class MvcVerifyCodeHandler : VerifyCodeHandler { public override void OnValidateCodeCreated(HttpContext context, string validateCode) { context.Session["validateCode"] = validateCode; } public override byte[] CreateValidateCode(string style) { ValidateCodeType createCode; switch (style) { case "type1": createCode = new ValidateCode_Style1(); break; default: createCode = new ValidateCode_Style1(); break; } var buffer = createCode.CreateImage(out var validateCode); OnValidateCodeCreated(HttpContext.Current, validateCode); return buffer; } }
-
在Controller处理验证码生成
/// <summary> /// 生成验证码 /// </summary> /// <param name="style">验证码样式</param> /// <returns>ActionResult</returns> [ ] public ActionResult CreateVerifyCode(string style) { VerifyCodeHandler verifyCodeHandler = new MvcVerifyCodeHandler(); var buffer = verifyCodeHandler.CreateValidateCode(style); return File(buffer, MimeTypes.ImageGif); }
-
前端页面调用
MasterChief.Infrastructure.MvcSample.Models.LoginViewModel @{ ViewBag.Title = "Login"; } <h2> .Title.</h2> <div class="row"> <div class=" col-md-8"> <section id="loginForm"> (Html.BeginForm("Login", "Account", new { ViewBag.ReturnUrl }, FormMethod.Post, new { = "form-horizontal", role = "form" })) { .AntiForgeryToken() <h4>Use a local account to log in.</h4> <hr /> .ValidationSummary(true, "", new { = "text-danger" }) <div class="form-group"> .LabelFor(m => m.Email, new { = "col-md-2 control-label" }) <div class="col-md-10"> .TextBoxFor(m => m.Email, new { = "form-control" }) .ValidationMessageFor(m => m.Email, "", new { = "text-danger" }) </div> </div> <div class="form-group"> .LabelFor(m => m.Password, new { = "col-md-2 control-label" }) <div class="col-md-10"> .PasswordFor(m => m.Password, new { = "form-control" }) .ValidationMessageFor(m => m.Password, "", new { = "text-danger" }) </div> </div> <div class="form-group"> <img id="valiCode" style="cursor: pointer;" class="col-md-2 control-label" src="~/Account/CreateVerifyCode" alt="验证码" /> <div class="col-md-10"> .TextBoxFor(m => m.VerifyCode, new { = "form-control" }) .ValidationMessageFor(m => m.VerifyCode, "", new { = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <div class="checkbox"> .CheckBoxFor(m => m.RememberMe) .LabelFor(m => m.RememberMe) </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Log in" class="btn btn-default" /> </div> </div> } </section> </div> <div class="col-md-4"> @*<section id="socialLoginForm"> .Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel {ReturnUrl = ViewBag.ReturnUrl}) </section>*@ </div> </div> Scripts{ <script type="text/javascript"> $(function () { $("#valiCode").bind("click", function () { this.src = "CreateVerifyCode?style=type1&time=" + (new Date()).getTime(); }); }); </script> }
-
后端代码使用
[public ActionResult Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) return View(model); if (string.Compare(Session["validateCode"].ToString(), model.VerifyCode, StringComparison.OrdinalIgnoreCase) != 0) ModelState.AddModelError("VerifyCode", "验证码验证不通过."); else return RedirectToAction("Index", "Home"); return View(); }
] [ ] [ ] -
运行效果
-