请问如何在ASP中获取客户端IP地址?NET时使用MVC 6。 请求。ServerVariables["REMOTE_ADDR"]无效。
当前回答
您还可以使用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; }
}
其他回答
试试这个。
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = ip.ToString();
}
}
从这个环节,就有了更好的解决方案。
在Startup.cs中,我们需要添加service-
public void ConfigureServices(IServiceCollection services)
{
........
services.AddHttpContextAccessor();
........
}
然后在任何控制器或任何地方,我们都需要像这样通过依赖注入来使用它
private IHttpContextAccessor HttpContextAccessor { get; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor)
: base(options)
{
Environment = env;
HttpContextAccessor = httpContextAccessor;
//this.Database.EnsureCreated();
}
然后得到这样的IP
IPAddress userIp = HttpContextAccessor.HttpContext.Connection.RemoteIpAddress;
在。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();
源
截至2021年9月- ASP。NET Core (5.x) MVC项目允许我在我的控制器中以这种方式获取IP地址:
Request.HttpContext.Connection.RemoteIpAddress
现在似乎比过去简单多了。
试试这个:
string remoteHost = $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}";