c# - 访问我的网站时如何获取客户端 IP 地址?
问题描述
我使用 dotnet core 3.1,我需要网站访问者的 IP 地址,但是当我尝试获取它时,返回的是服务器的 IP,而不是客户端。这是我使用的代码:
var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
这将返回 null。然后我尝试使用第三方网站获取我的 IP 地址。所以我这样做了:
WebRequest request = WebRequest.Create("https://api.ipify.org/");
这也将返回服务器的 IP 地址,而不是客户端。然后我尝试了这个:
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
和这个:
string localIP = string.Empty;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address.ToString();
}
但它们返回本地 IP 地址。返回本地IP.ToString();
并且某些代码行HTTPContext.Current.Request.UserHostAddress
或ServerVariables["REMOTE_ADDR"]
在 dotnet 核心中无效。请问有什么建议吗?
解决方案
I'm assuming that you are running the website not by directly exposing Kesterl
to the end clients but under some reverse proxy (IIS/nginx). In that case for Connection.RemoteIpAddress
to work property you have to configure the application by adding something like following code in the startup:
app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor })
推荐阅读
- php - 从 laravel 5.8 中的文本框中获取值
- android - 运行 Kotlin 单元和 UI 测试时,1 或 2 个新测试总是失败
- sql-server - select from @variable 如何在 from 之后使用变量
- python - 为什么二维数组只取最后两个输入整数?
- php - 如何在 Symfony 的控制器中包含 php 代码?
- reactjs - 我可以将函数(并获取其 ReturnType)传递给通用 TypeScript 类型吗?
- python - 推断时测量 keras/tf 上的层执行时间的最佳方法是什么?
- haskell - 如何查询默认方法的类型?
- c# - 在表单中处理自定义内存控件
- angular - Angular 中的 Ng2-Charts:轴的显示属性是否支持“自动”