Asp Net Web API 2.1 get client IP address
Following link might help you. Here's code from the following link.
reference : getting-the-client-ip-via-asp-net-web-api
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)request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
else if (HttpContext.Current != null)
{
return HttpContext.Current.Request.UserHostAddress;
}
else
{
return null;
}
}
}
}
Another way of doing this is below.
reference: how-to-access-the-client-s-ip-address
For web hosted version
string clientAddress = HttpContext.Current.Request.UserHostAddress;
For self hosted
object property;
Request.Properties.TryGetValue(typeof(RemoteEndpointMessageProperty).FullName, out property);
RemoteEndpointMessageProperty remoteProperty = property as RemoteEndpointMessageProperty;
How do I get client IP address in ASP.NET Core?
The API has been updated. Not sure when it changed but according to Damien Edwards in late December, you can now do this:
var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;
Find Client Public IP Address Inside Controller of rest web API with out calling external api
Check below code this must return you IP address of client
protected string GetUser_IP()
{
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
return VisitorsIPAddr;
}
For more help: Get public IP Address
Get client's IP address in ASP.NET Core 2.2
Inject IHttpContextAccessor
And put the below snippet
var result = string.Empty;
//first try to get IP address from the forwarded header
if (_httpContextAccessor.HttpContext.Request.Headers != null)
{
//the X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a client
//connecting to a web server through an HTTP proxy or load balancer
var forwardedHeader = _httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"];
if (!StringValues.IsNullOrEmpty(forwardedHeader))
result = forwardedHeader.FirstOrDefault();
}
//if this header not exists try get connection remote IP address
if (string.IsNullOrEmpty(result) && _httpContextAccessor.HttpContext.Connection.RemoteIpAddress != null)
result = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
I think it may work.
How to get user IP address in API model in ASP.NET Core 2.1?
You're breaking SOLID here. It's not appropriate for you model to know about HttpContext
or how to retrieve a remote IP address from that. The logic you want to encapsulate in your model simply needs an IP address, so that is what you should give it. This can either be provided in the constructor of your model class or just as a param to the particular method(s) that need to utilize it. For example, create a method like:
public void GeolocateByIP(string ip)
{
// do geolocation
}
In your controller action, then, you simply do something like:
model.GeolocateByIP(HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString());
Related Topics
What Are the Limitations of SQLdependency
Console.Writeline and Generic List
How to Reconcile Idisposable and Ioc
How to Round to the Nearest Whole Number in C#
What Is Point of Ssl If Fiddler 2 Can Decrypt All Calls Over Https
Handling Exceptions, Is This a Good Way
How to Remove All White Space from the Beginning or End of a String
Linq to SQL Multiple Tables Left Outer Join
Anonymous Type Result from SQL Query Execution Entity Framework
The Type Must Be a Reference Type in Order to Use It as Parameter 'T' in the Generic Type or Method
Retrieve System Uptime Using C#
The Input Is Not a Valid Base-64 String as It Contains a Non-Base 64 Character
Why Do We Need the New Keyword and Why Is the Default Behavior to Hide and Not Override
Raise Event Thread Safely - Best Practice
What Is Quicker, Switch on String or Elseif on Type
Why Is Inserting Entities in Ef 4.1 So Slow Compared to Objectcontext