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


当前回答

要在。net Core中获取IP地址和主机名,在控制器中输入以下代码:

var addlist = Dns.GetHostEntry(Dns.GetHostName());
string GetHostName = addlist.HostName.ToString();
string GetIPV6 = addlist.AddressList[0].ToString();
string GetIPV4 = addlist.AddressList[1].ToString();

其他回答

在IIS上使用负载均衡器运行。net core(3.1.4)不能与其他建议的解决方案一起工作。

手动读取X-Forwarded-For报头可以。 这段代码假设这个报头包含一个IP。

IPAddress ip;
var headers = Request.Headers.ToList();
if (headers.Exists((kvp) => kvp.Key == "X-Forwarded-For"))
{
    // when running behind a load balancer you can expect this header
    var header = headers.First((kvp) => kvp.Key == "X-Forwarded-For").Value.ToString();
    // in case the IP contains a port, remove ':' and everything after
    ip = IPAddress.Parse(header.Remove(header.IndexOf(':')));
}
else
{
    // this will always have a value (running locally in development won't have the header)
    ip = Request.HttpContext.Connection.RemoteIpAddress;
}

感谢@JawadAlShaikh和@BozoJoe指出IP可以包含一个端口,x - forward - for可以包含多个IP。

这适用于我(DotNetCore 2.1)

[HttpGet]
public string Get() 
{
    var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
    return remoteIpAddress.ToString();
}
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);

在我的情况下,我用docker和nginx作为反向代理在DigitalOcean上运行DotNet Core 2.2 Web应用程序。使用Startup.cs中的这段代码,我可以获得客户端IP

app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.All,
            RequireHeaderSymmetry = false,
            ForwardLimit = null,
            KnownNetworks = { new IPNetwork(IPAddress.Parse("::ffff:172.17.0.1"), 104) }
        });

::ffff:172.17.0.1是我在使用之前获得的ip

Request.HttpContext.Connection.RemoteIpAddress.ToString();

运行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中指定其网关。