HttpContextExtension.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Security.Claims;
  2. namespace Library.Extensions
  3. {
  4. public static class HttpContextExtension
  5. {
  6. // 회원 ID 조회
  7. public static int GetMemberID(this HttpContext context)
  8. {
  9. return int.TryParse(context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : 0;
  10. }
  11. // 회원 이름 조회
  12. public static string? UserName(this HttpContext context) => context.User.Identity?.Name;
  13. // 이전 요청 URL 조회
  14. public static string? GetReferer(this HttpContext context)
  15. {
  16. if (context.Request.Headers.TryGetValue("Referer", out var referer) && !string.IsNullOrWhiteSpace(referer))
  17. {
  18. return referer.ToString();
  19. }
  20. return null;
  21. }
  22. // Client IP 조회
  23. public static string? GetClientIP(this HttpContext context)
  24. {
  25. var forwardedFor = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
  26. if (!string.IsNullOrWhiteSpace(forwardedFor))
  27. {
  28. return forwardedFor;
  29. }
  30. return context.Connection.RemoteIpAddress?.ToString();
  31. }
  32. // User-agent 조회
  33. public static string? GetUserAgent(this HttpContext context)
  34. {
  35. if (context.Request.Headers.TryGetValue("User-Agent", out var userAgent) && !string.IsNullOrWhiteSpace(userAgent))
  36. {
  37. return userAgent.ToString();
  38. }
  39. return null;
  40. }
  41. // 상관관계 ID 조회
  42. public static string GetCorrelationID(this HttpContext context) => context.TraceIdentifier;
  43. }
  44. }