IsEmailAttribute.cs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. using DnsClient;
  2. using Masuit.Tools.Config;
  3. using System;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Text.RegularExpressions;
  8. namespace Masuit.Tools.Core.Validator;
  9. /// <summary>
  10. /// 邮箱校验
  11. /// </summary>
  12. public class IsEmailAttribute : ValidationAttribute
  13. {
  14. private readonly bool _valid;
  15. private readonly string _customMessage;
  16. /// <summary>
  17. /// 域白名单
  18. /// </summary>
  19. private string WhiteList { get; set; }
  20. /// <summary>
  21. /// 域黑名单
  22. /// </summary>
  23. private string BlockList { get; set; }
  24. /// <summary>
  25. /// 是否允许为空
  26. /// </summary>
  27. public bool AllowEmpty { get; set; }
  28. /// <summary>
  29. /// 可在配置文件AppSetting节中添加EmailDomainWhiteList配置邮箱域名白名单,EmailDomainBlockList配置邮箱域名黑名单,英文分号(;)或感叹号(!)或逗号(,)分隔,每个单独的元素支持正则表达式
  30. /// </summary>
  31. /// <param name="valid">是否检查邮箱的有效性</param>
  32. /// <param name="customMessage">自定义错误消息</param>
  33. public IsEmailAttribute(bool valid = true, string customMessage = null)
  34. {
  35. _valid = valid;
  36. _customMessage = customMessage;
  37. }
  38. /// <summary>
  39. /// 邮箱校验
  40. /// </summary>
  41. /// <param name="value"></param>
  42. /// <returns></returns>
  43. public override bool IsValid(object value)
  44. {
  45. WhiteList = Regex.Replace(ConfigHelper.GetConfigOrDefault("EmailDomainWhiteList"), @"(\w)\.([a-z]+),?", @"$1\.$2!").Trim('!');
  46. BlockList = Regex.Replace(ConfigHelper.GetConfigOrDefault("EmailDomainBlockList"), @"(\w)\.([a-z]+),?", @"$1\.$2!").Trim('!');
  47. if (AllowEmpty)
  48. {
  49. switch (value)
  50. {
  51. case null:
  52. case string s when string.IsNullOrEmpty(s):
  53. return true;
  54. }
  55. }
  56. if (value == null)
  57. {
  58. ErrorMessage = _customMessage ?? "邮箱不能为空!";
  59. return false;
  60. }
  61. var email = (string)value;
  62. if (email.Length < 7)
  63. {
  64. ErrorMessage = _customMessage ?? "您输入的邮箱格式不正确!";
  65. return false;
  66. }
  67. if (email.Length > 256)
  68. {
  69. ErrorMessage = _customMessage ?? "您输入的邮箱无效,请使用真实有效的邮箱地址!";
  70. return false;
  71. }
  72. if (!string.IsNullOrEmpty(WhiteList) && WhiteList.Split('!').Any(item => Regex.IsMatch(email, item)))
  73. {
  74. return true;
  75. }
  76. if (!string.IsNullOrEmpty(BlockList) && BlockList.Split(new[] { '!', ';' }, StringSplitOptions.RemoveEmptyEntries).Any(item => Regex.IsMatch(email, item)))
  77. {
  78. ErrorMessage = _customMessage ?? "您输入的邮箱无效,请使用真实有效的邮箱地址!";
  79. return false;
  80. }
  81. var isMatch = email.MatchEmail().isMatch;
  82. if (isMatch && _valid)
  83. {
  84. var nslookup = new LookupClient();
  85. var records = nslookup.Query(email.Split('@')[1], QueryType.MX).Answers.MxRecords().ToList();
  86. if (!string.IsNullOrEmpty(BlockList) && records.Any(r => BlockList.Split('!').Any(item => Regex.IsMatch(r.Exchange.Value, item))))
  87. {
  88. ErrorMessage = _customMessage ?? "您输入的邮箱无效,请使用真实有效的邮箱地址!";
  89. return false;
  90. }
  91. var task = records.SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
  92. {
  93. if (t.IsCanceled || t.IsFaulted)
  94. {
  95. return new[] { IPAddress.Loopback };
  96. }
  97. return t.Result;
  98. }));
  99. isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
  100. }
  101. if (isMatch)
  102. {
  103. return true;
  104. }
  105. ErrorMessage = _customMessage ?? "您输入的邮箱格式不正确!";
  106. return false;
  107. }
  108. }