请问如何在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;
}
其他回答
在项目。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
可以添加一些回退逻辑来处理负载均衡器的存在。
此外,通过检查,即使没有负载均衡器,X-Forwarded-For报头也会被设置(可能是因为额外的Kestrel层?):
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.IsNullOrWhitespace())
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提供。
在。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();
源
在我的情况下,我用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();
这适用于我(DotNetCore 2.1)
[HttpGet]
public string Get()
{
var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
return remoteIpAddress.ToString();
}