123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ProjectManagementSystem.WebApi.Extensions
- {
- public static class HttpRequestMessageExtensions
- {
- private const string HttpContext = "MS_HttpContext";
- private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
- private const string OwinContext = "MS_OwinContext";
- public static string GetClientIpAddress(this System.Net.Http.HttpRequestMessage request)
- {
- // Self-hosting. Needs reference to System.ServiceModel.dll.
- if (request.Properties.TryGetValue(RemoteEndpointMessage, out dynamic remoteEndpoint))
- {
- if (remoteEndpoint != null)
- {
- return remoteEndpoint.Address;
- }
- }
- // Self-hosting using Owin. Needs reference to Microsoft.Owin.dll.
- if (request.Properties.TryGetValue(OwinContext, out dynamic owinContext))
- {
- if (owinContext != null)
- {
- return owinContext.Request.RemoteIpAddress;
- }
- }
- // Web-hosting. Needs reference to System.Web.dll
- if (request.Properties.TryGetValue(HttpContext, out dynamic ctx))
- {
- if (ctx != null)
- {
- return ctx.Request.UserHostAddress;
- }
- }
- return null;
- }
- }
- }
|