Search code examples
asp.net-corehttpasp.net-core-mvcip

ASP.NET Core: How to get remote IP address?


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?


Solution

  • 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)