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


当前回答

试试这个:

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

其他回答

在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 ()

事情是这样的。

首先,在。net Core 1.0中 使用Microsoft.AspNetCore.Http.Features添加;到控制器 然后里面的相关方法:

var ip = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();

我读了其他几个答案,因为它使用了小写的httpContext,导致VS使用Microsoft.AspNetCore添加。Http,而不是适当的使用,或与HttpContext(编译器也是误导)。

可以添加一些回退逻辑来处理负载均衡器的存在。

此外,通过检查,即使没有负载均衡器,X-Forwarded-For报头也会被设置(可能是因为额外的Kestrel层?):

public string GetRequestIP(bool tryUseXForwardHeader = true)
{
    string ip = null;

    // todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For

    // X-Forwarded-For (csv list):  Using the First entry in the list seems to work
    // for 99% of cases however it has been suggested that a better (although tedious)
    // approach might be to read each IP from right to left and use the first public IP.
    // http://stackoverflow.com/a/43554000/538763
    //
    if (tryUseXForwardHeader)
        ip = GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault();

    // RemoteIpAddress is always null in DNX RC1 Update1 (bug).
    if (ip.IsNullOrWhitespace() && _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress != null)
        ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

    if (ip.IsNullOrWhitespace())
        ip = GetHeaderValueAs<string>("REMOTE_ADDR");

    // _httpContextAccessor.HttpContext?.Request?.Host this is the local host.

    if (ip.IsNullOrWhitespace())
        throw new Exception("Unable to determine caller's IP.");

    return ip;
}

public T GetHeaderValueAs<T>(string headerName)
{
    StringValues values;

    if (_httpContextAccessor.HttpContext?.Request?.Headers?.TryGetValue(headerName, out values) ?? false)
    {
        string rawValues = values.ToString();   // writes out as Csv when there are multiple.

        if (!rawValues.IsNullOrWhitespace())
            return (T)Convert.ChangeType(values.ToString(), typeof(T));
    }
    return default(T);
}

public static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false)
{
    if (string.IsNullOrWhiteSpace(csvList))
        return nullOrWhitespaceInputReturnsNull ? null : new List<string>();

    return csvList
        .TrimEnd(',')
        .Split(',')
        .AsEnumerable<string>()
        .Select(s => s.Trim())
        .ToList();
}

public static bool IsNullOrWhitespace(this string s)
{
    return String.IsNullOrWhiteSpace(s);
}

假设_httpContextAccessor通过DI提供。

也可以从外部服务获取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; }
}

API已经更新。不知道它什么时候改变了,但根据达米安·爱德华兹在12月底的说法,你现在可以这样做:

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;