gpt4 book ai didi

c# - 在Docker中运行的ASP .Net Core 2.0中获取用户IP

转载 作者:行者123 更新时间:2023-12-02 19:07:17 24 4
gpt4 key购买 nike

我尝试在Asp.Net Core 2.0 Web应用程序中获取用户IP。该应用程序在Docker容器中运行。
出于测试目的,我启动了一个新的Web api项目,并将此代码添加到“启动配置”方法的顶部。

app.Run(async (context) =>
{
try
{
StringBuilder requestBuilder = new StringBuilder();

var remoteIp = context.Connection.RemoteIpAddress;
string remoteIpstring = remoteIp != null ? remoteIp.ToString() : "-";
requestBuilder.Append(string.Format("remoteIp={0}\n", remoteIpstring));

string remotePort = context.Connection.RemotePort.ToString();
requestBuilder.Append(string.Format("remotePort={0}\n", remotePort));

var serverIp = context.Connection.LocalIpAddress;
string serverIpstring = serverIp != null ? serverIp.ToString() : "-";
requestBuilder.Append(string.Format("serverIp={0}\n", serverIpstring));

string serverPort = context.Connection.LocalPort.ToString();
requestBuilder.Append(string.Format("serverPort={0}\n", serverPort));

foreach (string key in context.Request.Headers.Keys)
{
string value = context.Request.Headers[key];
requestBuilder.Append(string.Format("{0}={1}\n", key, value));
}

await context.Response.WriteAsync(requestBuilder.ToString());
}
catch (Exception e)
{
Console.WriteLine(e);
}
});

我不知道为什么,但是当我检索RemoteIpAddress时,我得到了Docker网络网关的IP。当我检索LocalIpAddress时,我得到了Docker的网络IPAddress。

如何获得用户的真实IP?

最佳答案

来自 header ,例如X-Forwarded-For。但是为此,您将需要一种将其应用于请求的机制,例如代理。
然后,您只需索取标题并提取值

以下是nginx作为代理的示例配置:

     location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

关于c# - 在Docker中运行的ASP .Net Core 2.0中获取用户IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48439071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com