HttpContextExtensions.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System.Net;
  2. using Microsoft.AspNetCore.Http;
  3. namespace MediaBrowser.Common.Extensions
  4. {
  5. /// <summary>
  6. /// Static class containing extension methods for <see cref="HttpContext"/>.
  7. /// </summary>
  8. public static class HttpContextExtensions
  9. {
  10. /// <summary>
  11. /// Checks the origin of the HTTP context.
  12. /// </summary>
  13. /// <param name="context">The incoming HTTP context.</param>
  14. /// <returns><c>true</c> if the request is coming from the same machine as is running the server, <c>false</c> otherwise.</returns>
  15. public static bool IsLocal(this HttpContext context)
  16. {
  17. return (context.Connection.LocalIpAddress is null
  18. && context.Connection.RemoteIpAddress is null)
  19. || Equals(context.Connection.LocalIpAddress, context.Connection.RemoteIpAddress);
  20. }
  21. /// <summary>
  22. /// Extracts the remote IP address of the caller of the HTTP context.
  23. /// </summary>
  24. /// <param name="context">The HTTP context.</param>
  25. /// <returns>The remote caller IP address.</returns>
  26. public static IPAddress GetNormalizedRemoteIP(this HttpContext context)
  27. {
  28. // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests)
  29. var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback;
  30. if (ip.IsIPv4MappedToIPv6)
  31. {
  32. ip = ip.MapToIPv4();
  33. }
  34. return ip;
  35. }
  36. }
  37. }