HttpContextExtensions.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Net;
  2. using MediaBrowser.Common.Net;
  3. using Microsoft.AspNetCore.Http;
  4. namespace MediaBrowser.Common.Extensions
  5. {
  6. /// <summary>
  7. /// Static class containing extension methods for <see cref="HttpContext"/>.
  8. /// </summary>
  9. public static class HttpContextExtensions
  10. {
  11. /// <summary>
  12. /// Checks the origin of the HTTP request.
  13. /// </summary>
  14. /// <param name="request">The incoming HTTP request.</param>
  15. /// <returns><c>true</c> if the request is coming from LAN, <c>false</c> otherwise.</returns>
  16. public static bool IsLocal(this HttpRequest request)
  17. {
  18. return (request.HttpContext.Connection.LocalIpAddress == null
  19. && request.HttpContext.Connection.RemoteIpAddress == null)
  20. || request.HttpContext.Connection.LocalIpAddress.Equals(request.HttpContext.Connection.RemoteIpAddress);
  21. }
  22. /// <summary>
  23. /// Extracts the remote IP address of the caller of the HTTP request.
  24. /// </summary>
  25. /// <param name="request">The HTTP request.</param>
  26. /// <returns>The remote caller IP address.</returns>
  27. public static string RemoteIp(this HttpRequest request)
  28. {
  29. var cachedRemoteIp = request.HttpContext.Items["RemoteIp"]?.ToString();
  30. if (!string.IsNullOrEmpty(cachedRemoteIp))
  31. {
  32. return cachedRemoteIp;
  33. }
  34. IPAddress ip;
  35. // "Real" remote ip might be in X-Forwarded-For of X-Real-Ip
  36. // (if the server is behind a reverse proxy for example)
  37. if (!IPAddress.TryParse(request.Headers[CustomHeaderNames.XForwardedFor].ToString(), out ip))
  38. {
  39. if (!IPAddress.TryParse(request.Headers[CustomHeaderNames.XRealIP].ToString(), out ip))
  40. {
  41. ip = request.HttpContext.Connection.RemoteIpAddress;
  42. // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests)
  43. ip ??= IPAddress.Loopback;
  44. }
  45. }
  46. if (ip.IsIPv4MappedToIPv6)
  47. {
  48. ip = ip.MapToIPv4();
  49. }
  50. var normalizedIp = ip.ToString();
  51. request.HttpContext.Items["RemoteIp"] = normalizedIp;
  52. return normalizedIp;
  53. }
  54. }
  55. }