请问如何在ASP中获取客户端IP地址?NET时使用MVC 6。 请求。ServerVariables["REMOTE_ADDR"]无效。
当前回答
API已经更新。不知道它什么时候改变了,但根据达米安·爱德华兹在12月底的说法,你现在可以这样做:
var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;
其他回答
您还可以使用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; }
}
首先,在。net Core 1.0中 使用Microsoft.AspNetCore.Http.Features添加;到控制器 然后里面的相关方法:
var ip = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();
我读了其他几个答案,因为它使用了小写的httpContext,导致VS使用Microsoft.AspNetCore添加。Http,而不是适当的使用,或与HttpContext(编译器也是误导)。
var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress;
试试这个。
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = ip.ToString();
}
}
@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;
}
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- .NET核心MVC页面更改后不刷新
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务