如何在ASP.NETCore中获取客户端IP地址

能否请您让我知道在使用 MVC 6 时如何在 ASP.NET 中获取客户端 IP地址。Request.ServerVariables["REMOTE_ADDR"]不起作用。

能否请您让我知道在使用 MVC 6 时如何在 ASP.NET 中获取客户端 IP地址。Request.ServerVariables["REMOTE_ADDR"]不起作用。

443

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

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;
158

在 project.json 中添加一个依赖项:

"Microsoft.AspNetCore.HttpOverrides": "2.2.0"

Startup.cs中,在Configure()方法中添加:

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
    ForwardedHeaders.XForwardedProto
});  

而且,当然:

using Microsoft.AspNetCore.HttpOverrides;

然后,我可以通过使用获得 IP:

Request.HttpContext.Connection.RemoteIpAddress

在我的情况下,在 VS 中调试时,我总是得到 IpV6 本地主机,但是当部署在 IIS 上时,我总是得到远程 IP。

一些有用的链接:How do I get client IP address in ASP.NET CORE?RemoteIpAddress is always null

::1可能是因为:

IIS 上的连接终止,然后转发到 v.next Web 服务器 Kestrel,因此与 Web 服务器的连接确实来自 localhost。(https://stackoverflow.com/a/35442401/5326387)

编辑 12 / 2020:感谢SolidSnake:截至 2020 年 12 月,最新版本为 2.2.0

编辑 06 / 2021:感谢Hakan Fıstık:在.NET 5 中,命名空间是 Microsoft.AspNetCore.Builder

104

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

此外,通过检查,X-Forwarded-For头碰巧在没有负载均衡器的情况下被设置(可能是因为额外的 Kestrel 层?):

public string GetRequestIP(bool tryUseXForwardHeader = true)
{
    string ip = null;
    // todo support new "Forwarded" header (2014) https://en..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 提供的。

21

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

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

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(18)
如何使用Python3.x获取网站的IP地址
上一篇
Angular6单元测试:如何使用test.ts运行业力测试
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(64条)