ASP.NET Core 3.1-如何获得客户端的IP地址?

问题描述 投票:0回答:2

我有一个Razor Page Web应用程序,正在记录用户的IP地址。由于某种原因,它返回的是IP地址,而不是客户端的用户IP地址。我相信它可能正在从服务器返回IP?

注意: 我已经在所有其他ASP.NET Web窗体应用程序中添加了用户登录,并且它正在记录正确的IP。这是我们唯一的ASP.NET Core应用程序,它将返回不同的IP。

我是否在ConfigureServices方法中缺少某些内容,从而阻止了该方法获取用户的IP地址?

我的代码来自启动类中的ConfigureServices方法:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<ForwardedHeadersOptions>(options =>
        {
            options.ForwardedHeaders =
            ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
        });

        services.AddRazorPages().AddRazorRuntimeCompilation();
        services.AddAntiforgery(option =>
        {
            option.HeaderName = "XSRF-TOKEN";
            option.SuppressXFrameOptionsHeader = false;
        });
        services.AddSession();
        services.AddMemoryCache();
    }

我也在这样的Configure方法中调用UserForwardedHeaders方法:

app.UseForwardedHeaders();

[我在获取IP地址时正在使用RemoteIPAddress:

 HttpContext.Connection.RemoteIpAddress.ToString() 
c# razor-pages httpcontext asp.net-core-3.1
2个回答
0
投票

在控制器操作中尝试以下操作:

Request.HttpContext.Connection.RemoteIpAddress.ToString();

0
投票

这是我在.NET Core 2.1 ASP.NET MVC应用程序中所做的事情

public static string GetIpAddressFromHttpRequest(HttpRequest httpRequest)
{
  string ipAddressString = string.Empty;
  if (httpRequest == null)
  {
    return ipAddressString;
  }
  if (httpRequest.Headers != null && httpRequest.Headers.Count > 0)
  {
    if (httpRequest.Headers.ContainsKey("X-Forwarded-For") == true)
    {
      string headerXForwardedFor = httpRequest.Headers["X-Forwarded-For"];
      if (string.IsNullOrEmpty(headerXForwardedFor) == false)
      {
        string xForwardedForIpAddress = headerXForwardedFor.Split(':')[0];
        if (string.IsNullOrEmpty(xForwardedForIpAddress) == false)
        {
          ipAddressString = xForwardedForIpAddress;
        }
      }
    }
  }
  else if (httpRequest.HttpContext == null ||
       httpRequest.HttpContext.Connection == null ||
       httpRequest.HttpContext.Connection.RemoteIpAddress == null)
  {
       ipAddressString = httpRequest.HttpContext.Connection.RemoteIpAddress.ToString();
  }
  return ipAddressString;
}

我的应用程序在Google Chrome浏览器中运行良好。我没有在其他浏览器中进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.