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


当前回答

var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress;

其他回答

@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;
}

在ASP。NET 2.1,在StartUp.cs中添加此服务:

services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

然后做3步:

在MVC控制器中定义一个变量 private IHttpContextAccessor _accessor DI转换为控制器的构造函数 IHttpContextAccessor访问器 { _accessor = accessor; } 检索IP地址 _accessor.HttpContext.Connection.RemoteIpAddress.ToString ()

事情是这样的。

这适用于我(DotNetCore 2.1)

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

试试这个:

string remoteHost = $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}";