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

时间:2015-02-22 23:29:11

标签: c# asp.net-core asp.net-core-mvc

使用MVC 6时,请告诉我如何在ASP.NET中获取客户端IP地址。Request.ServerVariables["REMOTE_ADDR"]不起作用。

17 个答案:

答案 0 :(得分:194)

API已更新。不确定它何时发生变化,但在12月下旬according to Damien Edwards,你现在可以这样做了:

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;

答案 1 :(得分:54)

可以添加一些回退逻辑来处理Load Balancer的存在。

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

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提供的。

答案 2 :(得分:52)

在project.json中添加依赖项:

"Microsoft.AspNetCore.HttpOverrides": "1.0.0"

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

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

当然还有:

using Microsoft.AspNetCore.HttpOverrides;

然后,我可以通过使用:

来获取IP
Request.HttpContext.Connection.RemoteIpAddress

在我的情况下,在VS中调试时我总是得到IpV6 localhost,但是当部署在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

答案 3 :(得分:16)

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

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

答案 4 :(得分:11)

names(dfb)<-c("cr.H.MN.8A","cr.H.MN.8B","cr.H.MR.8A","cr.H.MR.8B","cr.H.MR2.8A","cr.H.MR2.8B")

答案 5 :(得分:5)

我发现,有些人发现您获得的IP地址是::: 1或0.0.0.1

这是问题所在,因为您尝试从自己的计算机上获取IP,并且C#试图返回IPv6感到困惑。

因此,我实现了@Johna(https://stackoverflow.com/a/41335701/812720)和@David(https://stackoverflow.com/a/8597351/812720)的答案,谢谢他们!

这里是解决方案:

  1. 在您的引用(依赖项/包)中添加Microsoft.AspNetCore.HttpOverrides包

  2. 在Startup.cs中添加此行

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // your current code
    
        // start code to add
        // to get ip address
        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });
        // end code to add
    
    }
    
  3. 要获取IP地址,请在您的任何Controller.cs中使用此代码。

    IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
    string result = "";
    if (remoteIpAddress != null)
    {
        // If we got an IPV6 address, then we need to ask the network for the IPV4 address 
        // This usually only happens when the browser is on the same machine as the server.
        if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
        {
            remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
    .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
        }
        result = remoteIpAddress.ToString();
    }
    

现在您可以从 remoteIpAddress 结果

获取IPv4地址

答案 6 :(得分:3)

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

unwrap()

然后执行3步:

  1. 在MVC控制器中定义变量

    services.AddHttpContextAccessor();
    services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
    
  2. DI到控制器的构造函数中

    private IHttpContextAccessor _accessor;
    
  3. 获取IP地址

    public SomeController(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
    

这是完成的方式。

答案 7 :(得分:2)

首先,在.Net Core 1.0中 将using Microsoft.AspNetCore.Http.Features;添加到控制器 然后在相关方法内:

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

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

答案 8 :(得分:2)

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

Source

答案 9 :(得分:1)

在.net核心中获取IP地址和主机名

将此代码放入控制器

执行以下步骤:

var addlist = Dns.GetHostEntry(Dns.GetHostName());
string GetHostName = addlist.HostName.ToString();
string GetIPV6 = addlist.AddressList[0].ToString();
string GetIPV4 = addlist.AddressList[1].ToString();

答案 10 :(得分:1)

在负载均衡器后面的.NET core上运行IIS(3.1.4)不能与其他建议的解决方案一起使用。

手动读取X-Forwarded-For标头即可。

IPAddress ip;
var headers = Request.Headers.ToList();
if (headers.Exists((kvp) => kvp.Key == "X-Forwarded-For"))
{
    // when running behind a load balancer you can expect this header
    var header = headers.First((kvp) => kvp.Key == "X-Forwarded-For").Value.ToString();
    ip = IPAddress.Parse(header);
}
else
{
    // this will always have a value (running locally in development won't have the header)
    ip = Request.HttpContext.Connection.RemoteIpAddress;
}

答案 11 :(得分:0)

@crokusek 的 answer 的简短版本

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

答案 12 :(得分:0)

this link 开始,有一个更好的解决方案。

在Startup.cs中,我们需要添加service-

public void ConfigureServices(IServiceCollection services)
{
    ........
    services.AddHttpContextAccessor();
    ........
}

然后在任何控制器或任何地方,我们需要像这样通过依赖注入来使用它-

private IHttpContextAccessor HttpContextAccessor { get; }

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor)
        : base(options)
{
    Environment = env;
    HttpContextAccessor = httpContextAccessor;
    //this.Database.EnsureCreated();
}

然后像这样获得IP-

IPAddress userIp = HttpContextAccessor.HttpContext.Connection.RemoteIpAddress;

答案 13 :(得分:0)

在Ubuntu上的Traefik反向代理后面运行ASP.NET Core 2.1,我需要在安装官方KnownProxies软件包后在Microsoft.AspNetCore.HttpOverrides中设置其网关IP

        var forwardedOptions = new ForwardedHeadersOptions {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor,
        };
        forwardedOptions.KnownProxies.Add(IPAddress.Parse("192.168.3.1"));
        app.UseForwardedHeaders(forwardedOptions);

根据the documentation,如果反向代理未在本地主机上运行,​​则需要这样做。 Traefik的docker-compose.yml已分配了一个静态IP地址:

networks:
  my-docker-network:
    ipv4_address: 192.168.3.2

或者,应确保已在此处定义了已知网络以在.NET Core中指定其网关。

答案 14 :(得分:0)

就我而言,我拥有在DigitalOcean上运行的DotNet Core 2.2 Web App,并使用docker和nginx作为反向代理。通过Startup.cs中的这段代码,我可以获得客户端IP

app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.All,
            RequireHeaderSymmetry = false,
            ForwardLimit = null,
            KnownNetworks = { new IPNetwork(IPAddress.Parse("::ffff:172.17.0.1"), 104) }
        });

:: ffff:172.17.0.1是我在使用

之前获得的IP
Request.HttpContext.Connection.RemoteIpAddress.ToString();

答案 15 :(得分:0)

这对我有用(DotNetCore 2.1)

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

答案 16 :(得分:-1)

尝试一下。

var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                 ipAddress = ip.ToString();
            }
        }