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

前端 未结 2 909
深忆病人
深忆病人 2021-02-03 13:42

I try to get remote (client) IP addres:

var ip = httpContext.Features.Get()?.RemoteIpAddress

But it works only fo

相关标签:
2条回答
  • 2021-02-03 13:54

    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.

    0 讨论(0)
  • 2021-02-03 14:05

    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)

    0 讨论(0)
提交回复
热议问题