首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在ASP.NET核心中获取客户端IP地址?

如何在ASP.NET核心中获取客户端IP地址?
EN

Stack Overflow用户
提问于 2015-02-23 07:29:11
回答 17查看 220.2K关注 0票数 295

你能告诉我在使用MVC6时如何在ASP.NET中获取客户端IP地址吗?Request.ServerVariables["REMOTE_ADDR"]不工作。

EN

回答 17

Stack Overflow用户

回答已采纳

发布于 2016-02-13 06:17:19

API已更新。不确定它是什么时候更改的,但在12月下旬的according to Damien Edwards中,您现在可以这样做:

代码语言:javascript
复制
var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;
票数 391
EN

Stack Overflow用户

发布于 2016-03-31 01:54:38

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

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

代码语言:javascript
复制
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);
}

假设通过DI提供_httpContextAccessor

票数 94
EN

Stack Overflow用户

发布于 2015-03-11 08:18:11

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

代码语言:javascript
复制
var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;
票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28664686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档