'ASP.NET Core 3.1 - How do I get a client's IP Address?
I have a Razor Page Web Application and am logging users' IP addresses. For some reason it is returning an IP address but not the client's user IP Address. I believe it may be returning the IP from the server?
Note: I have added user logging in all of the other ASP.NET Web Forms applications and it's logging the correct IPs. This is our only ASP.NET Core application and it's returning a different IP.
Am I missing something in the ConfigureServices method that's preventing it from getting the users' ip address?
My code from the ConfigureServices method in the startup class:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddRazorPages().AddRazorRuntimeCompilation();
services.AddAntiforgery(option =>
{
option.HeaderName = "XSRF-TOKEN";
option.SuppressXFrameOptionsHeader = false;
});
services.AddSession();
services.AddMemoryCache();
}
I am also calling the UserForwardedHeaders method in the Configure method as such:
app.UseForwardedHeaders();
I am using RemoteIPAddress when retrieving the IP Address:
HttpContext.Connection.RemoteIpAddress.ToString()
Solution 1:[1]
var ipAddr = HttpContext.Connection.RemoteIpAddress.ToString();
This will return {::1} when you execute the code at local. After deployment to the Test or Production server, it will get your client's IP
var deviceName = Dns.GetHostEntry(HttpContext.Connection.RemoteIpAddress).HostName;
It is for finding the Computer Name for the intranet application.
Solution 2:[2]
This is what I did in .NET Core 2.1 ASP.NET MVC Application
public static string GetIpAddressFromHttpRequest(HttpRequest httpRequest)
{
string ipAddressString = string.Empty;
if (httpRequest == null)
{
return ipAddressString;
}
if (httpRequest.Headers != null && httpRequest.Headers.Count > 0)
{
if (httpRequest.Headers.ContainsKey("X-Forwarded-For") == true)
{
string headerXForwardedFor = httpRequest.Headers["X-Forwarded-For"];
if (string.IsNullOrEmpty(headerXForwardedFor) == false)
{
string xForwardedForIpAddress = headerXForwardedFor.Split(':')[0];
if (string.IsNullOrEmpty(xForwardedForIpAddress) == false)
{
ipAddressString = xForwardedForIpAddress;
}
}
}
}
else if (httpRequest.HttpContext == null ||
httpRequest.HttpContext.Connection == null ||
httpRequest.HttpContext.Connection.RemoteIpAddress == null)
{
ipAddressString = httpRequest.HttpContext.Connection.RemoteIpAddress.ToString();
}
return ipAddressString;
}
My application working good in Google Chrome. I did not test in another browsers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Syscall |
| Solution 2 | Ziggler |
