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" };
}