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


当前回答

这适用于我(DotNetCore 2.1)

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

其他回答

您还可以使用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 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();

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

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

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

在ASP。NET 2.1,在StartUp.cs中添加此服务:

services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

然后做3步:

在MVC控制器中定义一个变量 private IHttpContextAccessor _accessor DI转换为控制器的构造函数 IHttpContextAccessor访问器 { _accessor = accessor; } 检索IP地址 _accessor.HttpContext.Connection.RemoteIpAddress.ToString ()

事情是这样的。