I try to get remote (client) IP addres:
var ip = httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress
But it works only for local requests (it will return ::1
value)
When I load page from remote machine the value is null. I investigated there is no IHttpConnectionFeature
in the Features
collection in this case.
Why? And how to get remote ip address correctly?
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.
Also called an IP safelist, an IP whitelist helps to ensure that our application's sensitive data is exposed only to IP addresses that we know and trust. An IP whitelist can be implemented in ASP.NET Core by using middleware or by using MVC action filters.
It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any. ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface. The HttpContextAccessor class implements it.
The simple answer is that: ::1 is the compressed format of IPV6 loopback address 0:0:0:0:0:0:0:1 . It is the equivalent of the IPV4 address 127.0. 0.1. Follow this answer to receive notifications. answered Dec 22, 2021 at 9:41.
Just try this code,
var ipAddress = HttpContext.Connection.RemoteIpAddress;
And if you have another computer in same LAN, try to connect with this pc but use user ip instead of localhost. Otherwise you will get always ::1 result.
I know that this post is old but I came here looking for the same question and finnaly I did this:
On project.json add dependency:
"Microsoft.AspNetCore.HttpOverrides": "1.0.0"
On Startup.cs, in the Configure method add:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
And, of course:
using Microsoft.AspNetCore.HttpOverrides;
Then, I got the ip like this:
Request.HttpContext.Connection.RemoteIpAddress
In my case, when debugging in VS I got always IpV6 localhost, but when deployed on an IIS I got always the remote IP.
Some useful links: How do I get client IP address in ASP.NET CORE? and RemoteIpAddress is always null
The ::1 may be because:
Connections termination at IIS, which then forwards to Kestrel, the v.next web server, so connections to the web server are indeed from localhost. (https://stackoverflow.com/a/35442401/5326387)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With