部署在Linux下,使用nginx做代理,但是还是读取不出来IP,请问各位大神怎么搞得?
public string getRemoteIp() { var ip = httpContextAccessor.HttpContext.Request.Headers["X-Original-For"].FirstOrDefault(); if (string.IsNullOrEmpty(ip)) { ip = "*.*.*.*"; } return ip; }
在ASP.NET Core中没有ServerVariables的对应实现,需要换一种方式,可以在HttpContext.Request.Headers中获取,需要注意的是key与ServerVariables方式不一样,ServerVariables中是"HTTP_X_FORWARDED_FOR",HttpContext.Request.Headers中是"X-Forwarded-For",示例代码如下:
public static class HttpContextExtension
{
public static string GetUserIp(this HttpContext context)
{
var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(ip))
{
ip = context.Connection.RemoteIpAddress.ToString();
}
return ip;
}
}
在Nginx中配置添加如下内容试试:
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
}
public string getRemoteIp()
{
var ip = HttpContext.Request.Headers["X-Original-For"].FirstOrDefault();
if (string.IsNullOrEmpty(ip))
{
ip = "...";
}
return ip;
}
http://localhost:5250/Default/home IP地址: ::1