HttpContextExtension.cs 1.8 KB

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