.NET6使WebApi獲取訪問者IP地址

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();

到此這篇關於.NET6使WebApi獲取訪問者IP地址的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: