HttpRequestMessageExtensions.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. // Web-hosting. Needs reference to System.Web.dll
  16. if (request.Properties.ContainsKey(HttpContext))
  17. {
  18. dynamic ctx = request.Properties[HttpContext];
  19. if (ctx != null)
  20. {
  21. return ctx.Request.UserHostAddress;
  22. }
  23. }
  24. // Self-hosting. Needs reference to System.ServiceModel.dll.
  25. if (request.Properties.ContainsKey(RemoteEndpointMessage))
  26. {
  27. dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
  28. if (remoteEndpoint != null)
  29. {
  30. return remoteEndpoint.Address;
  31. }
  32. }
  33. // Self-hosting using Owin. Needs reference to Microsoft.Owin.dll.
  34. if (request.Properties.ContainsKey(OwinContext))
  35. {
  36. dynamic owinContext = request.Properties[OwinContext];
  37. if (owinContext != null)
  38. {
  39. return owinContext.Request.RemoteIpAddress;
  40. }
  41. }
  42. return null;
  43. }
  44. }
  45. }