[open source] fast build verification code

Keywords: ASP.NET Session Javascript

Instructions

  1. Support WebForm and Asp.Net Mvc to build verification code

  2. Project source code: MasterChief.DotNet.Infrastructure.VerifyCode

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

  4. Welcome Star, welcome PR;

How to use

  1. To customize the verification code style, you only need to implement the ValidateCodeType abstract class

    /// <summary>
     ///Picture verification code abstract class
     /// </summary>
     public abstract class ValidateCodeType
     {
         #region Methods
    
         /// <summary>
         ///Create verification code abstract method
         /// </summary>
         ///< param name = "validatacode" > validation code < / param >
         ///< returns > byte array < / returns >
         public abstract byte[] CreateImage(out string validataCode);
    
         #endregion Methods
    
         #region Constructors
    
         #endregion Constructors
    
         #region Properties
    
         /// <summary>
         ///Verification code type name
         /// </summary>
         public abstract string Name { get; }
    
         /// <summary>
         ///Verification code Tooltip
         /// </summary>
         public virtual string Tip => "Please enter the characters in the picture";
    
         /// <summary>
         ///Type name
         /// </summary>
         public string Type => GetType().Name;
    
         #endregion Properties
     }
  2. Instructions in WebForm

    1. New general handler

      /// <summary>
      ///Summary description for 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. Front end page call

      <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="I can't see clearly. Change it" 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. Back end page usage

      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 = "Verification code verification failed.";
                  ErrorMessage.Visible = true;
              }
              else
              {
                  Response.Redirect("Default.aspx");
              }
          }
      }
    4. Operation effect

  3. Instructions for use in Asp.Net Mvc

    1. Create a new mvcvverifycodehandler and implement the abstract class VerifyCodeHandler

      /// <summary>
        ///Processing generation of Mvc program verification code
        /// </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. Processing verification code generation in Controller

      /// <summary>
      ///Generate verification code
      /// </summary>
      ///< param name = "style" > verification code 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. Front end page call

      @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="Verification Code" />
                          <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. Back end code usage

      [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", "Verification code verification failed.");
          else
              return RedirectToAction("Index", "Home");
      
          return View();
      }
    5. Operation effect

Posted by spooke2k on Sat, 30 Nov 2019 23:27:23 -0800