如何在ASP.NET CORE中获取客户端IP地址?

你可以请让我知道如何获得客户端的IP地址在ASP.NET中使用MVC 6. Request.ServerVariables["REMOTE_ADDR"]不起作用。

该API已更新。 不知道什么时候改变,但根据达米安·爱德华兹在十二月下旬,你现在可以这样做:

 var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress; 

可以添加一些回退逻辑来处理Load Balancer的存在。

另外,通过检查,即使没有Load Balancer(可能是因为额外的Kestrel层?), X-Forwarded-For头部也恰好被设置:

 public string GetRequestIP(bool tryUseXForwardHeader = true) { string ip = null; // todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For // X-Forwarded-For (csv list): Using the First entry in the list seems to work // for 99% of cases however it has been suggested that a better (although tedious) // approach might be to read each IP from right to left and use the first public IP. // http://stackoverflow.com/a/43554000/538763 // if (tryUseXForwardHeader) ip = GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault(); // RemoteIpAddress is always null in DNX RC1 Update1 (bug). if (ip.IsNullOrWhitespace() && _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress != null) ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(); if (ip.IsNullOrWhitespace()) ip = GetHeaderValueAs<string>("REMOTE_ADDR"); // _httpContextAccessor.HttpContext?.Request?.Host this is the local host. if (ip.IsNullOrWhitespace()) throw new Exception("Unable to determine caller's IP."); return ip; } public T GetHeaderValueAs<T>(string headerName) { StringValues values; if (_httpContextAccessor.HttpContext?.Request?.Headers?.TryGetValue(headerName, out values) ?? false) { string rawValues = values.ToString(); // writes out as Csv when there are multiple. if (!rawValues.IsNullOrEmpty()) return (T)Convert.ChangeType(values.ToString(), typeof(T)); } return default(T); } public static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false) { if (string.IsNullOrWhiteSpace(csvList)) return nullOrWhitespaceInputReturnsNull ? null : new List<string>(); return csvList .TrimEnd(',') .Split(',') .AsEnumerable<string>() .Select(s => s.Trim()) .ToList(); } public static bool IsNullOrWhitespace(this string s) { return String.IsNullOrWhiteSpace(s); } 

假设_httpContextAccessor是通过DI提供的。

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

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

在project.json中添加一个依赖项:

 "Microsoft.AspNetCore.HttpOverrides": "1.0.0" 

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

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

而且当然:

 using Microsoft.AspNetCore.HttpOverrides; 

然后,我可以通过使用以下方法获取IP:

 Request.HttpContext.Connection.RemoteIpAddress 

在我的情况下,在VS中debugging时总是使用IpV6本地主机,但是当部署在IIS上时,我总是使用远程IP。

一些有用的链接: 如何在ASP.NET CORE中获取客户端IP地址? 并且RemoteIpAddress始终为空

::1也许是因为:

IIS中的连接终止,然后转发到vstnext web服务器Kestrel,所以到web服务器的连接确实来自localhost。 ( https://stackoverflow.com/a/35442401/5326387

首先在.Net Core 1.0中添加using Microsoft.AspNetCore.Http.Features; 给控制器然后在相关的方法里面:

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

我读了几个其他的答案,因为它使用小写的httpContext,导致VS添加使用Microsoft.AspNetCore.Http,而不是适当的使用,或与HttpContext(编译器也是误导),编译失败。