Skip to content

Instantly share code, notes, and snippets.

@mii9000
Last active June 12, 2023 08:12
Show Gist options
  • Save mii9000/e7dc81805d77e4d6d8bc to your computer and use it in GitHub Desktop.
Save mii9000/e7dc81805d77e4d6d8bc to your computer and use it in GitHub Desktop.
How to get Client IP from a request in Web API #webapi
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;
namespace Trikks.Controllers.Api
{
public class IpController : ApiController
{
public string GetIp()
{
return GetClientIp();
}
private string GetClientIp(HttpRequestMessage request = null)
{
request = request ?? 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)this.Request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
else if (HttpContext.Current != null)
{
return HttpContext.Current.Request.UserHostAddress;
}
else
{
return null;
}
}
}
}
@aha056
Copy link

aha056 commented Jun 12, 2023

Not Working at server level

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment