简介:
本文主要介绍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" };
}
了解更多分析及数据抓取可查看:
http://data.yisurvey.com:8989/
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。