HttpRequestMessageExtensions.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ProjectManagementSystem.WebApi.Extensions
  7. {
  8. public static class HttpRequestMessageExtensions
  9. {
  10. private const string HttpContext = "MS_HttpContext";
  11. private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
  12. private const string OwinContext = "MS_OwinContext";
  13. public static string GetClientIpAddress(this System.Net.Http.HttpRequestMessage request)
  14. {
  15. // Self-hosting. Needs reference to System.ServiceModel.dll.
  16. if (request.Properties.TryGetValue(RemoteEndpointMessage, out dynamic remoteEndpoint))
  17. {
  18. if (remoteEndpoint != null)
  19. {
  20. return remoteEndpoint.Address;
  21. }
  22. }
  23. // Self-hosting using Owin. Needs reference to Microsoft.Owin.dll.
  24. if (request.Properties.TryGetValue(OwinContext, out dynamic owinContext))
  25. {
  26. if (owinContext != null)
  27. {
  28. return owinContext.Request.RemoteIpAddress;
  29. }
  30. }
  31. // Web-hosting. Needs reference to System.Web.dll
  32. if (request.Properties.TryGetValue(HttpContext, out dynamic ctx))
  33. {
  34. if (ctx != null)
  35. {
  36. return ctx.Request.UserHostAddress;
  37. }
  38. }
  39. return null;
  40. }
  41. }
  42. }