请问如何在ASP中获取客户端IP地址?NET时使用MVC 6。 请求。ServerVariables["REMOTE_ADDR"]无效。


当前回答

要在。net Core中获取IP地址和主机名,在控制器中输入以下代码:

var addlist = Dns.GetHostEntry(Dns.GetHostName());
string GetHostName = addlist.HostName.ToString();
string GetIPV6 = addlist.AddressList[0].ToString();
string GetIPV4 = addlist.AddressList[1].ToString();

其他回答

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

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

也可以从外部服务获取IP。

public string GetIP()
{
    HttpClient client = new HttpClient();
    var result = client.GetStringAsync("https://jsonip.com/").Result;
    var ip = JsonSerializer.Deserialize<RemoteIPDto>(result.ToString()).IP;
    return ip;
}

RemoteIPDto类在哪里

public class RemoteIPDto
{
    [JsonPropertyName("ip")]
    public string IP { get; set; }
    [JsonPropertyName("geo-ip")]
    public string GeoIp { get; set; }
    [JsonPropertyName("API Help")]
    public string ApiHelp { get; set; }
}

这适用于我(DotNetCore 2.1)

[HttpGet]
public string Get() 
{
    var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
    return remoteIpAddress.ToString();
}

要在。net Core中获取IP地址和主机名,在控制器中输入以下代码:

var addlist = Dns.GetHostEntry(Dns.GetHostName());
string GetHostName = addlist.HostName.ToString();
string GetIPV6 = addlist.AddressList[0].ToString();
string GetIPV4 = addlist.AddressList[1].ToString();