How to Get Client User IP Address In ASP.NET Core Web API
How to Get User IP Address In ASP.NET Core Web API.
This page summarize information about how to retrieve client and server IP address in ASP.NET Core web applications.
Get client user IP address
Client IP address can be retrieved via HttpContext.Connection object. This properties exist in both Razor page model and ASP.NET MVC controller. Property RemoteIpAddress is the client IP address. The returned object (System.Net.IpAddress) can be used to check whether it is IPV4 or IPV6 address.
public string ClientIPAddr { get; private set; }
public async Task<IActionResult> OnGetAsync()
{
// Retrieve client IP address through HttpContext.Connection
ClientIPAddr = HttpContext.Connection.RemoteIpAddress?.ToString();
return Page();
}
Access HttpContext in ASP.NET Core
Refer to documentation Access HttpContext in ASP.NET Core | Microsoft Docs to understand the details of accessing HttpContext in ASP.NET Core applications.
For requests forwarded by proxy servers
This means the client IP of HttpContext.Connection.RemoteIpAddress is the IP address of the proxy servers.
If the HTTP request is first processed by a reverse proxy server, the only approach to get the client IP address in server side is to look into the forwarded headers if there are any. For example, Retrieve Client IP Address in cloudflare with HTTP Ingress.
var headers = this._httpContextAccessor.HttpContext.Request.Headers;
if (headers.ContainsKey("X-Forwarded-For"))
{
ipv6address = headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0];
}
ipv6address = headers["CF-Connecting-IP"].ToString();
Comments
Comments are closed