aspnet zero 12 添加登录 验证码

      aspnet zero 自带的验证码是基于Google ,国内当前无法使用,只能替换国内的。实现后的界面如下图:

 

Install-Package Lazy.Captcha.Core
  • 验证码后端代码
public interface ICaptchaAppService : IApplicationService
    {
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="id">Id</param>
        Stream Captcha(string id);

        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="id">Id</param>
        /// <param name="code">Code</param>
        /// <returns></returns>
        Task ValidateAsync(string id,string code);
    }
    
    public class CaptchaAppService : SISAppServiceBase, ICaptchaAppService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ICaptcha _captcha;

        public CaptchaAppService(ICaptcha captcha, IHttpContextAccessor httpContextAccessor)
        {
            _captcha = captcha;
            _httpContextAccessor = httpContextAccessor;
        }

        public Stream Captcha(string id)
        {
            var captcha = _captcha.Generate(id, 30);
            var stream = new MemoryStream(captcha.Bytes);
            return stream;
        }


        public async Task ValidateAsync(string id, string code)
        {
            var httpContext = _httpContextAccessor.HttpContext;
            if (httpContext == null)
            {
                throw new Exception("RecaptchaValidator should be used in a valid HTTP context!");
            }

            if (id.IsNullOrEmpty() || code.IsNullOrEmpty())
            {
                throw new UserFriendlyException(L("CaptchaCanNotBeEmpty"));
            }

            var result = _captcha.Validate(id, code);

            if (!result)
            {
                throw new UserFriendlyException(L("IncorrectCaptchaAnswer"));
            }

            await Task.CompletedTask;

        }
    }
  • 登录验证代码
      [HttpPost]
      public virtual async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl = "",
          string returnUrlHash = "", string ss = "")
      {
          returnUrl = NormalizeReturnUrl(returnUrl);
          if (!string.IsNullOrWhiteSpace(returnUrlHash))
          {
              returnUrl = returnUrl + returnUrlHash;
          }

          string id = HttpContext.Request.Form["id"];
          string captcha = HttpContext.Request.Form["captcha"];
          await _captchaAppservice.ValidateAsync(id, captcha);

          var loginResult = await GetLoginResultAsync(
              loginModel.UsernameOrEmailAddress,
              loginModel.Password,
              GetTenancyNameOrNull()
          );
          
         //其它代码省略 .....
      }
  • 前端HTML 和Javascript 代码
<div class="mb-5">
            <div class="row">
                <div class="col-6">
                    <input type="text" class="form-control form-control-solid h-auto  px-6 rounded-lg fs-6"
                        placeholder="验证码"  name="captcha" id="captcha" 
                        style="padding-top:1.0rem !important;padding-bottom:1.0rem !important;"/>
                </div>
                <div class="col-6">
                    <img src="/" width="100" height="50" id="captchaImage"/>
                </div>
            </div>
        </div>
  function guid() {
      function S4() {
          return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      }
      return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
  }

  function bingImage() {

      var id = guid();
      $("#guid").val(id);
      var src = abp.appPath + "captcha/captcha?id="+ id;
      $("#captchaImage").attr("src", src);
  }

  $("#captchaImage").click(function () {
      bingImage();
  });
  return {
      init: function () {
          bingImage();  //在原有的代码基础上新增初始化加载img
      handleLogin();
    },

 

posted @ 2024-03-11 14:06  在 水 一 方  阅读(17)  评论(0编辑  收藏  举报