请问如何在ASP中获取客户端IP地址?NET时使用MVC 6。 请求。ServerVariables["REMOTE_ADDR"]无效。


当前回答

根据官方文档,如果你使用Apache或Nginx集成,以下代码应该添加到启动。ConfigureServices方法。

// using Microsoft.AspNetCore.HttpOverrides;

    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | 
            ForwardedHeaders.XForwardedProto;
        // Only loopback proxies are allowed by default.
        // Clear that restriction because forwarders are enabled by explicit 
        // configuration.
        options.KnownNetworks.Clear();
        options.KnownProxies.Clear();
    });

最重要的是,在配置方法中使用

app.UseForwardedHeaders();

进一步假设在nginx conf文件中,在一个位置内,使用

proxy_set_header   Host $host;
proxy_set_header   X-Real-IP $remote_addr;
proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header   X-Forwarded-Host $server_name;

现在X-Forwarded-For中的第一个条目将是真正的客户端IP。

重要:如果你想保护应用程序,不允许攻击者注入x - forward - for,请阅读这个答案。

请参见转发Linux和非iis反向代理方案、配置Nginx和处理无效报头

其他回答

运行ASP。在Ubuntu上的Traefik反向代理后面的NET Core 2.1,我需要在安装官方的Microsoft.AspNetCore.HttpOverrides包后在knownproxy中设置它的网关IP

        var forwardedOptions = new ForwardedHeadersOptions {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor,
        };
        forwardedOptions.KnownProxies.Add(IPAddress.Parse("192.168.3.1"));
        app.UseForwardedHeaders(forwardedOptions);

根据文档,如果反向代理没有在本地主机上运行,这是必需的。docker-compose。Traefik . yml已分配静态IP地址:

networks:
  my-docker-network:
    ipv4_address: 192.168.3.2

或者,它应该足以确保在这里定义了一个已知的网络,并在. net Core中指定其网关。

注意:当使用localhost时,IP地址总是“0.0.0.1”,但当我在AWS EC2实例上使用Nginx托管应用程序时,我收到了正确的IP地址。

将以下包添加到您的项目中:

"Microsoft.AspNetCore.HttpOverrides": "2.2.0"

然后在Startup.cs中的Configure()方法中添加以下内容(确保将其放在app.UseStaticFiles()和app.UseRouting()之前)

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
    
// app.UseStaticFiles();
// app.UseRouting();

然后在你的控制器类中,你可以使用下面的代码获取IP地址:

IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4()?.ToString();

我发现,你们中的一些人发现你们得到的IP地址是:::1或0.0.0.1

这是一个问题,因为你试图从你自己的机器获取IP,而c#试图返回IPv6的混乱。

所以,我实现了来自@Johna (https://stackoverflow.com/a/41335701/812720)和@David (https://stackoverflow.com/a/8597351/812720)的答案,感谢他们!

下面是解决方案:

add Microsoft.AspNetCore.HttpOverrides Package in your References (Dependencies/Packages) add this line in Startup.cs public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // your current code // start code to add // to get ip address app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); // end code to add } to get IPAddress, use this code in any of your Controller.cs IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress; string result = ""; if (remoteIpAddress != null) { // If we got an IPV6 address, then we need to ask the network for the IPV4 address // This usually only happens when the browser is on the same machine as the server. if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); } result = remoteIpAddress.ToString(); }

现在你可以从remoteIpAddress或result获取IPv4地址

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

public string GetClientIPAddress(HttpContext context)
    {
        string ip = string.Empty;
if (!string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"]))
        {
            ip = context.Request.Headers["X-Forwarded-For"];
        }
        else
        {
            ip = context.Request.HttpContext.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString();
        }
        return ip;
    }

你想获取Ip地址;

GetClientIPAddress(HttpContext);

您可以使用IHttpConnectionFeature来获取此信息。

var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;