asp.net core获取真实客户端IP地址

本篇记录如何使用asp.net core获取真实的IP地址。

实际在使用的过程中,如果需要获取客户端地址,

是没有办法直接通过传统ASP.Net使用Request.xxx的方式获取的。

那么就需要进行如下操作:

1、新增一个依赖注入

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

2、控制器

private readonly IHttpContextAccessor _httpContextAccessor;
   public TestController( IHttpContextAccessor httpContextAccessor) 
    {
            _httpContextAccessor = httpContextAccessor;
}

3、使用

 string ipaddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

通过上面的方法可以正常获取到IP地址。

但是如果有使用Nginx做反向代理的话,使用上面的方式获取到的IP会是127.0.0.1,无法获取到真实的IP地址,

所以如果使用Nginx做反向代理,则应该使用下面的方式:

 if (Request.Headers.ContainsKey("X-Real-IP"))
     {
       sb.AppendLine($"X-Real-IP:{Request.Headers["X-Real-IP"].ToString()}");
     }

     if (Request.Headers.ContainsKey("X-Forwarded-For"))
     {
       sb.AppendLine($"X-Forwarded-For:{Request.Headers["X-Forwarded-For"].ToString()}");
     }

因为实际使用,我们是无法通过RemoteIpAddress直接获取到真实的客户端地址的。

如果一定要使用,那么可以通过添加中间件的方式

public class RealIpMiddleware
{
    private readonly RequestDelegate _next;

    public RealIpMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context)
    {
        var headers = context.Request.Headers;
        if (headers.ContainsKey("X-Forwarded-For"))
        {
            context.Connection.RemoteIpAddress=IPAddress.Parse(headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]);
        }
        return _next(context);
    }
}

在Startup中的Configura添加下面一句

app.UseMiddleware<RealIpMiddleware>();

这样既可正常使用RemoteIpAddress获取Nginx反向代理后的IP地址了。

Over!

 

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章