ASP.NET Core 中获取客户端(Client)IP的方法

本文详细介绍了在ASP.NETCore中通过两种方法获取客户端IP,包括在Startup.cs中配置ForwardedHeadersOptions以处理转发头,以及使用IHttpContextAccessor在控制器中访问HTTP上下文。同时提醒读者注意合法使用技术,避免非法用途。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介:
本文主要介绍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/
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值