本文主要介绍ASP.NET Core中获取客户端(Client)IP的方法代码,以及负载均衡的情况获取客户端IP。

1、第一种方法

1)在Startup.cs中ConfigureSerivces中配置

services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

2)获取IP代码

string remoteIpAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
if (Request.Headers.ContainsKey("X-Forwarded-For"))
remoteIpAddress = Request.Headers["X-Forwarded-For"];

2、第二种方法

1)在Startup.cs中ConfigureSerivces中配置

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

2)在控制器(Controller)中获取IP

private IHttpContextAccessor _accessor;
public ValuesController(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public IEnumerable<string> Get()
{
var ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
return new string[] { ip, "value2" };
}

推荐文档