VB.net 2010 視頻教程 VB.net 2010 視頻教程 VB.net 2010 視頻教程
SQL Server 2008 視頻教程 c#入門經典教程 Visual Basic從門到精通視頻教程
  • ASP.net教程之[開源]快速構建驗證碼

  • 2019-04-18 22:40 來源:未知

魔兽世界wow www.geyjm.icu 使用說明

  1. 支持WebForm以及Asp.Net Mvc構建驗證碼

  2. 項目源碼:MasterChief.DotNet.Infrastructure.VerifyCode

  3. Nuget:Install-Package MasterChief.DotNet.Infrastructure.VerifyCode

  4. 歡迎Star,歡迎Issues;

如何使用#

  1. 自定義驗證碼樣式,只需要實現ValidateCodeType抽象類即可

    
    			
    Copy
    /// <summary> /// 圖片驗證碼抽象類 /// </summary> public abstract class ValidateCodeType { #region Methods /// <summary> /// 創建驗證碼抽象方法 /// </summary> /// <param name="validataCode">驗證code</param> /// <returns>Byte數組</returns> public abstract byte[] CreateImage(out string validataCode); #endregion Methods #region Constructors #endregion Constructors #region Properties /// <summary> /// 驗證碼類型名稱 /// </summary> public abstract string Name { get; } /// <summary> /// 驗證碼Tooltip /// </summary> public virtual string Tip => "請輸入圖片中的字符"; /// <summary> /// 類型名稱 /// </summary> public string Type => GetType().Name; #endregion Properties }
  2. 在WebForm使用說明

    1. 新建一般處理程序

      
      					
      Copy
      /// <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; } }
    2. 前端頁面調用

      
      					
      Copy
      <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>
    3. 后端頁面使用

      
      					
      Copy
      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"); } } }
    4. 運行效果

  3. 在Asp.Net Mvc使用說明

    1. 新建MvcVerifyCodeHandler,并實現抽象類VerifyCodeHandler

      
      					
      Copy
      /// <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; } }
    2. 在Controller處理驗證碼生成

      
      					
      Copy
      /// <summary> /// 生成驗證碼 /// </summary> /// <param name="style">驗證碼樣式</param> /// <returns>ActionResult</returns> [AllowAnonymous] public ActionResult CreateVerifyCode(string style) { VerifyCodeHandler verifyCodeHandler = new MvcVerifyCodeHandler(); var buffer = verifyCodeHandler.CreateValidateCode(style); return File(buffer, MimeTypes.ImageGif); }
    3. 前端頁面調用

      
      					
      Copy
      @model MasterChief.Infrastructure.MvcSample.Models.LoginViewModel @{ ViewBag.Title = "Login"; } <h2>@ViewBag.Title.</h2> <div class="row"> <div class=" col-md-8"> <section id="loginForm"> @using (Html.BeginForm("Login", "Account", new { ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() <h4>Use a local account to log in.</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Password, "", new { @class = "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"> @Html.TextBoxFor(m => m.VerifyCode, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.VerifyCode, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <div class="checkbox"> @Html.CheckBoxFor(m => m.RememberMe) @Html.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"> @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel {ReturnUrl = ViewBag.ReturnUrl}) </section>*@ </div> </div> @section Scripts{ <script type="text/javascript"> $(function () { $("#valiCode").bind("click", function () { this.src = "CreateVerifyCode?style=type1&time=" + (new Date()).getTime(); }); }); </script> }
    4. 后端代碼使用

      
      					
      Copy
      [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] 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(); }
    5. 運行效果

作者:YanZhiwei

出處:https://www.cnblogs.com/MeetYan/p/10656129.html

本站使用「署名 4.0 國際」創作共享協議,轉載請在文章明顯位置注明作者及出處。


相關教程