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!

 

  

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