依次获取三种来源的ip(X-Real-IP、X-Forwarded-For、RemoteIp)
1.X-Real-IP
(1)是自定义的http头,由服务器自行在http请求的请求头上添加。
(2)如有多个服务器进行添加,则保留最后一个。
(3)如果我方服务器没有赋值,则此ip不可信。相反,在我方外层服务器覆盖ip数值,则可以认为是请求者的真实ip,就可信。
2.X-Forwarded-For
(1)是自定义的http头,由服务器自行在http请求的请求头上添加。
(2)如有多个服务器进行添加,则以逗号分隔保留全部ip。
(3)如果我方服务器没有赋值,则此ip不可信。相反,在我方外层服务器追加ip数值,则可以认为最后一个ip是请求者的真实ip,就可信。
3.RemoteIp
(1)是已有的信息
(2)服务器不能改变
(3)此ip可信,但拿到的只是进行连接的服务器的ip,如果我方有在用服务器转发,会拿到我方转发服务器的ip,意义就不大。
// ip
string ip="";
string type = "";
// context 是 从过滤器拿的ActionExecutingContext
try
{
if (string.IsNullOrEmpty(ip))
{
ip = context.HttpContext.Request.Headers["X-Real-IP"].FirstOrDefault();
type = "X-Real-IP";
}
if (string.IsNullOrEmpty(ip))
{
ip = context.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
type = "X-Forwarded-For";
}
if (string.IsNullOrEmpty(ip))
{
ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
type = "RemoteIp";
}
// 判断是否多个ip
if (ip.IndexOf(",") != -1)
{
//有“,”,估计多个代理。取最后一个的IP。
string[] temparyip = ip.Split(",");
ip = temparyip[temparyip.Length - 1].Trim();
}
// 去除::ffff:
if (ip.IndexOf("::ffff:") != -1)
{
ip = ip.Substring(7);
}
if (string.IsNullOrEmpty(ip))
{
ip = "NoGet";
type = "NoGet";
}
}
catch
{
ip = "NoGet";
type = "NoGet";
}