c# - 在 ASP.NET CORE Web API 中获取客户端 IP 地址有问题吗?

标签 c# .net-core asp.net-core-webapi

我在 ASP.NET CORE Web API 中使用以下方法获取服务器 IP 地址而不是客户端 IP。 请告诉我哪里出错了。我之前在 asp mvc 中使用过 ServerVariables["HTTP_X_FORWARDED_FOR"] 并且工作正常。

private string DetectIPAddress(HttpRequest request)
{
    var _IP = "RemoteIp:" + request.HttpContext.Connection.RemoteIpAddress.ToString() + " - LocalIpAddress:" +
                  request.HttpContext.Connection.LocalIpAddress;
    try
    {
        _IP += " IP.AddressFamily:" + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1].ToString();

        _IP += " HostName:" + Dns.GetHostEntry(Dns.GetHostName()).HostName;

    }
    catch (Exception e)
    {

    }

    return _IP;
}

最佳答案

获取客户端 IP 听起来很容易,但实际上我已经尝试获取客户端 IP 很多个小时,直到找到 this gist extension method。在@Voodoo 的评论中帮助了我。我想让它更加突出,因此创建一个单独的答案。它适用于 AWS fargate 上的 .NET 5,可能具有某种负载均衡器直通,其中 RemoteIpAddress 单独不起作用。

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 ip = HttpContext.GetRemoteIPAddress().ToString();

关于c# - 在 ASP.NET CORE Web API 中获取客户端 IP 地址有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56525043/

相关文章:

c# - 如果没有等待最后一个 MoveNextAsync() 任务,IAsyncEnumerator<T>.DisposeAsync() 是否应该抛出异常?

c# - OData 端点不返回实体的所有属性

c# - Asp.net 计数用户尝试

javascript - 我可以使用javascript来检测asp.net的事件吗?

c# - 在 .NET Core/.NET 5+ 中使用 TransactionScope 和 SQL 连接池时如何避免 PlatformNotSupportedException

c# - XUnit Gherkin 快,有没有办法改变 Visual Studio 中的测试资源管理器渲染场景的方式?

c# - Entity Framework 仅保存我的一些字段

c# - 如何在同一网址上使用 [FromBody] 和 [FromForm]?

c# - 在用户控件内单击按钮更改 View

c# - 如何将列标题绑定(bind)到 ViewModel 中的属性? (WPF MVVM)