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


当前回答

@crokusek回答的简短版本

public string GetUserIP(HttpRequest req)
{
    var ip = req.Headers["X-Forwarded-For"].FirstOrDefault();

    if (!string.IsNullOrWhiteSpace(ip)) ip = ip.Split(',')[0];

    if (string.IsNullOrWhiteSpace(ip)) ip = Convert.ToString(req.HttpContext.Connection.RemoteIpAddress);

    if (string.IsNullOrWhiteSpace(ip)) ip = req.Headers["REMOTE_ADDR"].FirstOrDefault();

    return ip;
}

其他回答

在。net 5中,我使用它通过AWS fargate上的容器来检索客户端IP。

public static class HttpContextExtensions
{
    //https://gist.github.com/jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36

    public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true)
    {
        if (allowForwarded)
        {
            string header = (context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? context.Request.Headers["X-Forwarded-For"].FirstOrDefault());
            if (IPAddress.TryParse(header, out IPAddress ip))
            {
                return ip;
            }
        }
        return context.Connection.RemoteIpAddress;
    }
}

你这样称呼它:

var ipFromExtensionMethod = HttpContext.GetRemoteIPAddress().ToString();

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

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

我发现,你们中的一些人发现你们得到的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地址

在项目。Json添加一个依赖:

"Microsoft.AspNetCore.HttpOverrides": "2.2.0"

在Startup.cs中,在Configure()方法中添加:

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

当然,还有:

using Microsoft.AspNetCore.HttpOverrides;

然后,我可以通过使用:

Request.HttpContext.Connection.RemoteIpAddress

在我的情况下,在VS中调试时,我总是得到IpV6 localhost,但在IIS上部署时,我总是得到远程IP。

一些有用的链接: 如何在ASP中获取客户端IP地址。网络核心?RemoteIpAddress为空

::1可能是因为:

连接终止在IIS,然后转发到Kestrel, v.next web服务器,因此连接到web服务器确实是从本地主机。(https://stackoverflow.com/a/35442401/5326387)

编辑12/2020:感谢SolidSnake:截至2020年12月,最新版本是2.2.0

Edit 06/2021:感谢Hakan fakhtik:在。net 5中,命名空间是Microsoft.AspNetCore.Builder

从这个环节,就有了更好的解决方案。

在Startup.cs中,我们需要添加service-

public void ConfigureServices(IServiceCollection services)
{
    ........
    services.AddHttpContextAccessor();
    ........
}

然后在任何控制器或任何地方,我们都需要像这样通过依赖注入来使用它

private IHttpContextAccessor HttpContextAccessor { get; }

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor)
        : base(options)
{
    Environment = env;
    HttpContextAccessor = httpContextAccessor;
    //this.Database.EnsureCreated();
}

然后得到这样的IP

IPAddress userIp = HttpContextAccessor.HttpContext.Connection.RemoteIpAddress;