IPUtil.cs 954 B

123456789101112131415161718192021222324252627282930313233
  1. using Microsoft.AspNetCore.Http;
  2. using System.Linq;
  3. namespace YBEE.EQM.Core;
  4. public static class IPUtil
  5. {
  6. /// <summary>
  7. /// 获取请求的ip4
  8. /// </summary>
  9. /// <param name="context"></param>
  10. /// <returns></returns>
  11. public static string GetRequestIPv4(this HttpContext context)
  12. {
  13. string ip = string.Empty;
  14. if (context.Connection.RemoteIpAddress != null)
  15. {
  16. if (context.Request.Headers.ContainsKey("X-Real-IP"))
  17. {
  18. ip = context.Request.Headers["X-Real-IP"].FirstOrDefault();
  19. }
  20. if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
  21. {
  22. ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
  23. }
  24. if (string.IsNullOrEmpty(ip))
  25. {
  26. ip = context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString();
  27. }
  28. }
  29. return ip;
  30. }
  31. }