LazyCaptchaSetup.cs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. using Lazy.Captcha.Core;
  10. using Lazy.Captcha.Core.Generator;
  11. using Lazy.Captcha.Core.Storage;
  12. using SkiaSharp;
  13. namespace Admin.NET.Core;
  14. public static class LazyCaptchaSetup
  15. {
  16. /// <summary>
  17. /// 验证码初始化
  18. /// </summary>
  19. /// <param name="services"></param>
  20. public static void AddLazyCaptcha(this IServiceCollection services)
  21. {
  22. services.AddCaptcha(App.Configuration);
  23. services.AddScoped<ICaptcha, RandomCaptcha>();
  24. }
  25. }
  26. /// <summary>
  27. /// 随机验证码
  28. /// </summary>
  29. public class RandomCaptcha : DefaultCaptcha
  30. {
  31. private static readonly Random random = new();
  32. private static readonly CaptchaType[] captchaTypes = Enum.GetValues<CaptchaType>();
  33. public RandomCaptcha(IOptionsSnapshot<CaptchaOptions> options, IStorage storage) : base(options, storage)
  34. {
  35. }
  36. /// <summary>
  37. /// 更新选项
  38. /// </summary>
  39. /// <param name="options"></param>
  40. protected override void ChangeOptions(CaptchaOptions options)
  41. {
  42. // 随机验证码类型
  43. options.CaptchaType = captchaTypes[10]; // captchaTypes[random.Next(0, captchaTypes.Length)];
  44. // 当是算数运算时,CodeLength是指运算数个数
  45. if (options.CaptchaType.IsArithmetic())
  46. {
  47. options.CodeLength = 2;
  48. }
  49. else
  50. {
  51. options.CodeLength = 4;
  52. }
  53. // 如果包含中文时,使用kaiti字体,否则文字乱码
  54. if (options.CaptchaType.ContainsChinese())
  55. {
  56. options.ImageOption.FontFamily = DefaultFontFamilys.Instance.Kaiti;
  57. options.ImageOption.FontSize = 24;
  58. }
  59. else
  60. {
  61. options.ImageOption.FontFamily = DefaultFontFamilys.Instance.Actionj;
  62. }
  63. options.IgnoreCase = true; // 忽略大小写
  64. options.ImageOption.Animation = random.Next(2) == 0; // 动静
  65. options.ImageOption.InterferenceLineCount = random.Next(1, 5); // 干扰线数量
  66. options.ImageOption.BubbleCount = random.Next(1, 5); // 气泡数量
  67. //options.ImageOption.BubbleMinRadius = 5; // 气泡最小半径
  68. //options.ImageOption.BubbleMaxRadius = 15; // 气泡最大半径
  69. //options.ImageOption.BubbleThickness = 1; // 气泡边沿厚度
  70. options.ImageOption.BackgroundColor = SKColors.White; // 背景色
  71. options.ImageOption.Width = 150; // 验证码宽度
  72. options.ImageOption.Height = 50; // 验证码高度
  73. options.ImageOption.FontSize = 36; // 字体大小
  74. //options.ImageOption.FontFamily = DefaultFontFamilys.Instance.Actionj; // 字体
  75. }
  76. }