Some times you will want to track the client who is calling your API and from which IP address the client made the call. Following method might help you to get client IP:
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;
private static string GetClientIp(HttpRequestMessage request)
{
if (request.Properties.ContainsKey("MS_HttpContext"))
{
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
{
RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
else if (HttpContext.Current != null)
{
return HttpContext.Current.Request.UserHostAddress;
}
else
{
return null;
}
}
In case of calling from local machine it will return ::1 otherwise the client IP address.
Happy Learning
https://www.guest-articles.com/education/free-1z0-1072-20-pdf-and-1z0-1072-20-practice-test-demo-21-11-2020
ReplyDeleteHow we'll call GetClientIp(HttpRequestMessage request)? How to get HttpRequestMessage value?
ReplyDelete