Asp.net-Core-Mvc

在 Asp.Net Core 核心中如何獲取網站的 IP 地址?

  • November 4, 2019

在網路表單中,如果我需要獲取網站伺服器的 IP 地址(例如用於日誌記錄),我可以從request.ServerVariables["LOCAL_ADDR"]

在 IIS 或 IIS Express 後面的 Kestral 中執行時,如何在 Asp.Net Core 中獲取它?

您可以使用HttpContext.Features.Get<IHttpConnectionFeature>()-文件

var httpConnectionFeature = httpContext.Features.Get<IHttpConnectionFeature>();
var localIpAddress = httpConnectionFeature?.LocalIpAddress;

這就是使用 .net core 2.1 對我有用的方法

根據您的需要調整正則表達式。我的產品 Web 伺服器在 10.168.xx 範圍內。我的開發機器在 10.60.xx 範圍內。

if(String.IsNullOrEmpty(localIpAddress))
{
   var ips = await System.Net.Dns.GetHostAddressesAsync(System.Net.Dns.GetHostName());

   string rgx = (env.IsDevelopment()) ? @"10{1}\.60{1}\..*" : @"10{1}\.168{1}\..*";
   var result = ips.FirstOrDefault(x => {
       Match m2 = Regex.Match(x.ToString(), rgx);
       return m2.Captures.Count >= 1;
   });
   localIpAddress = result.ToString();
}

雖然最後我只是使用了,System.Net.Dns.GetHostName()因為我真的不需要 IP 地址。

引用自:https://stackoverflow.com/questions/40347426