欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[开源]快速构建验证码

程序员文章站 2022-07-11 09:16:23
使用说明 1. 支持WebForm以及Asp.Net Mvc构建验证码 2. 项目源码: " MasterChief.DotNet.Infrastructure.VerifyCode " 3. Nuget:Install Package MasterChief.DotNet.Infrastructu ......

使用说明

  1. 支持webform以及asp.net mvc构建验证码

  2. 项目源码:masterchief.dotnet.infrastructure.verifycode

  3. nuget:install-package masterchief.dotnet.infrastructure.verifycode

  4. 欢迎star,欢迎pr;

如何使用

  1. 自定义验证码样式,只需要实现validatecodetype抽象类即可

    /// <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. 新建一般处理程序

      /// <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. 前端页面调用

      <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. 后端页面使用

      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

      /// <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处理验证码生成

      /// <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. 前端页面调用

      @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. 后端代码使用

      [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. 运行效果

      [开源]快速构建验证码