NETCORE - WebApi 获取客户端IP地址
NETCORE - WebApi 获取客户端IP地址
1. 环境
NET6 WebApi
2. 在Program.cs 中注入
//获取客户端IP builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
3. 在Controller中调用
[Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly ILogger<ValuesController> LoggerValue; private readonly IHttpContextAccessor httpContextAccessor; public ValuesController(ILogger<ValuesController> logger, IHttpContextAccessor _HttpContextAccessor) { this.LoggerValue = logger; this.httpContextAccessor = _HttpContextAccessor; } [HttpGet] public IActionResult Get() { var ipCurrent = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(); return Ok(ipCurrent); } }
参考:https://wenku.baidu.com/view/ede9713a51d380eb6294dd88d0d233d4b14e3ffa.html?_wkts_=1690167032137&bdQuery=net6+%E8%AF%BB%E5%8F%96ip