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


当前回答

试试这个:

string remoteHost = $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}";

其他回答

要在。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();
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

public string GetClientIPAddress(HttpContext context)
    {
        string ip = string.Empty;
if (!string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"]))
        {
            ip = context.Request.Headers["X-Forwarded-For"];
        }
        else
        {
            ip = context.Request.HttpContext.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString();
        }
        return ip;
    }

你想获取Ip地址;

GetClientIPAddress(HttpContext);

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; }
}

这适用于我(DotNetCore 2.1)

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