.NET6 WebApi 获取访问者IP地址

时间:2024-03-09 17:07:10

Program.cs文件中

//获取IP使用
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Controller中

private readonly IHttpContextAccessor httpContextAccessor;
public YangController(IHttpContextAccessor _httpContextAccessor)
{
  httpContextAccessor = _httpContextAccessor;
}

var ip=httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();