• .NET 6 实现滑动验证码(九)、搭建验证码API服务端


    上一篇介绍了实现验证码生成的方法跟验证方法。本篇文章介绍如何在项目中使用。

    目录

    项目配置

    在实际应用中,我们可以添加打包好的.nupkg文件,也可以使用添加现有项目的方式,把源码添加到现有项目中。
    appsettings.json中,添加ImageCaptcha节点。

    "ImageCaptcha": {
        "ExpiresIn": 60,
        "CacheKey": "", 
        "Tolerant": 0.02, 
        "Backgrounds": [
          {
            "Type": "file",
            "Data": "wwwroot/captcha/background/1.jpg"
          }
        ],
        "Templates": [
          {
            "Slider": {
              "Type": "file",
              "Data": "wwwroot/captcha/template/1/slider.png"
            },
            "Notch": {
              "Type": "file",
              "Data": "wwwroot/captcha/template/1/notch.png"
            }
          }
        ]
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    ExpiresIn:缓存过期时长,单位秒。
    CacheKey:缓存名称前缀。
    Tolerant:容错值,凹槽位置与实际滑动位置匹配容错范围。
    Backgrounds:验证码背景图
    Templates:凹槽与滑块模板,如果不配置此项。使用默认的嵌入资源。需要注意的是,Templates下的滑块与凹槽,必须成对出现。

    配置完appsettings.json后,进行代码配置,Program.cs中:

    简单配置

    builder.Services.AddSlideCaptcha(configuration);
    
    • 1

    详细配置:

    builder.Services.AddSlideCaptcha(configuration, options =>
    {
        options.Backgrounds.Add(new Resource(FileResourceHandler.TYPE, @"wwwroot/captcha/background/1.jpg"));
        options.Templates.Add(
            TemplatePair.Create(
                new Resource(FileResourceHandler.TYPE, @"wwwroot/captcha/template/1/slider.png"),
                new Resource(FileResourceHandler.TYPE, @"wwwroot/captcha/template/1/notch.png"),
                CaptchaTypeConstant.SLIDER
                )
            );
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    配置完成后,定义接口:ApiController

    
        [Route("api/[controller]")]
        public class CaptchaController : ControllerBase
        {
            private readonly ICaptcha _captcha;
    
            public CaptchaController(ICaptcha captcha)
            {
                _captcha = captcha;
            }
    
            public async Task<AjaxResult<CaptchaData>> Captcha(string type = "SLIDER")
            {
                var captcha = await _captcha.GenerateCaptchaImageAsync(type);
    
                return new AjaxResult<CaptchaData>
                {
                    data = captcha,
                    success = true
                };
            }
    
            [HttpPost]
            public AjaxResult Validate(string id, SlideTrack track)
            {
                var result = new AjaxResult();
                track.StartTime = track.StartTime.ToLocalTime();
                track.EndTime = track.EndTime.ToLocalTime();
                ValidateResult validateResult = _captcha.Validate(id, track);
                //成功
                if (validateResult.Result == ValidateResultType.Success)
                {
                    result.message = "验证成功";
                    result.success = true;
                    return result;
                }
                //超时
                if (validateResult.Result == ValidateResultType.Timeout)
                {
                    result.success = false;
                    result.message = "验证超时, 请重新操作";
                    return result;
                }
                //失败
                if (validateResult.Result == ValidateResultType.ValidateFail)
                {
                    result.success = false;
                    result.message = "验证未通过, 请重新操作";
                    return result;
                }
                result.success = false;
                result.message = "未知错误, 请重新操作";
                return result;
            }
        }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    代码中AjaxResult.cs

    public class AjaxResult
        {
            /// 
            /// 是否成功
            /// 
            public bool success { get; set; } = true;
    
            /// 
            /// 错误代码
            /// 
            public int code { get; set; } = 0;
    
            /// 
            /// 返回消息
            /// 
            public string message { get; set; }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    AjaxResult.T.cs

     public class AjaxResult<T> : AjaxResult
        {
            /// 
            /// 返回数据
            /// 
            public T data { get; set; }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    我们完成了在实际项目中搭建滑动验证码的服务。
    下一篇,介绍前端滑动验证码的实现,前端验证码组件我写了2个,1个是普通HTML+CSS+Jquery的。另一个是vue3的。

    下载方式:
    点击下方公众号卡片,关注我,回复captcha 免费领取!

  • 相关阅读:
    Spring5 框架概述
    vscode - 添加新项目到远程仓库(gitee)
    TypeScript手写+项目实际
    ELK专栏之ES快速入门-01
    将矩阵按对角线排序(c++题解)
    Java开发学习(一)----初识Spring及其核心概念
    套接字的多种可选项
    社交媒体变革者:剖析Facebook对在线互动的贡献
    Redis 事务
    Mysql语法四:索引查找和了解何为事务
  • 原文地址:https://blog.csdn.net/sd2208464/article/details/127946346