请问如何在ASP中获取客户端IP地址?NET时使用MVC 6。 请求。ServerVariables["REMOTE_ADDR"]无效。
当前回答
注意:当使用localhost时,IP地址总是“0.0.0.1”,但当我在AWS EC2实例上使用Nginx托管应用程序时,我收到了正确的IP地址。
将以下包添加到您的项目中:
"Microsoft.AspNetCore.HttpOverrides": "2.2.0"
然后在Startup.cs中的Configure()方法中添加以下内容(确保将其放在app.UseStaticFiles()和app.UseRouting()之前)
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
// app.UseStaticFiles();
// app.UseRouting();
然后在你的控制器类中,你可以使用下面的代码获取IP地址:
IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4()?.ToString();
其他回答
可以添加一些回退逻辑来处理负载均衡器的存在。
此外,通过检查,即使没有负载均衡器,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提供。
我发现,你们中的一些人发现你们得到的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地址
您还可以使用api.db-ip.com web服务获取IP地址和位置。
这项服务是免费的,但有一个限制:每天1000次请求。
public string GetRemoteIP()
{
HttpClient client = new HttpClient();
var result = client.GetStringAsync("https://api.db-ip.com/v2/free/self").Result;
var ip = JsonSerializer.Deserialize<RemoteIPDto>(result.ToString()).IP;
return ip;
}
public static string GetUserAddress()
{
HttpClient client = new HttpClient();
var result = client.GetStringAsync("https://api.db-ip.com/v2/free/self").Result;
var location = result.ToString();
return remoteAddress;
}
RemoteIPDto类在哪里
public class RemoteIPDto
{
[JsonPropertyName("ipAddress")]
public string IP { get; set; }
[JsonPropertyName("continentCode")]
public string ContinentCode { get; set; }
[JsonPropertyName("continentName")]
public string ContinentName { get; set; }
[JsonPropertyName("countryCode")]
public string CountryCode { get; set; }
[JsonPropertyName("countryName")]
public string CountryName { get; set; }
[JsonPropertyName("city")]
public string City { get; set; }
}
注意:当使用localhost时,IP地址总是“0.0.0.1”,但当我在AWS EC2实例上使用Nginx托管应用程序时,我收到了正确的IP地址。
将以下包添加到您的项目中:
"Microsoft.AspNetCore.HttpOverrides": "2.2.0"
然后在Startup.cs中的Configure()方法中添加以下内容(确保将其放在app.UseStaticFiles()和app.UseRouting()之前)
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
// app.UseStaticFiles();
// app.UseRouting();
然后在你的控制器类中,你可以使用下面的代码获取IP地址:
IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4()?.ToString();
var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress;
推荐文章
- 随机字符串生成器返回相同的字符串
- 为什么Func<T,bool>而不是Predicate<T>?
- .NET中的Map和Reduce
- 我如何能使一个组合框不可编辑的。net ?
- .NET反射的成本有多高?
- 实体框架回滚并移除不良迁移
- 将流转换为字符串并返回
- 在c#中检查字符串是否只包含数字的最快方法
- IEquatable和重写Object.Equals()之间的区别是什么?
- 创建一个堆栈大小为默认值50倍的线程有什么危险?
- 转换JSON字符串到JSON对象c#
- 显示两个datetime值之间的小时差值
- 如何设置enum为空
- 选择Enum类型的默认值而无需更改值
- 我如何设置在一个组合框中选择的项目,以匹配我的字符串使用c# ?