[C#] ASP.NET Core 6.0 - 在 Azure AppService 取得 Client 端的 IP

2022-09-07

今天筆記一個之前用到的東西,就是在 Azure AppService 上取得用戶的 IP 

當初是因為我們許多服務在上面,有時候我們要根據進入系統者的人做一些邏輯上的限制

所以就有這需求,就筆記一下


其實用法也很簡單,就不贅述了,剛剛也在重新測試這案例到 App Service 上也正常

public void OnGet() { Result = GetClientIP(this.HttpContext); } public static string GetClientIP(HttpContext httpContext) { string ip; if (!string.IsNullOrEmpty(httpContext.Request.Headers["X-Azure-SocketIP"])) { ip = httpContext.Request.Headers["X-Azure-SocketIP"].ToString().Split(',').FirstOrDefault(); ip = System.Net.IPAddress.Parse(ip).MapToIPv4().ToString(); } else { ip = httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); } return ip; }


來源也不可考了謝謝開源的各位大大





當麻許的碎念筆記 2014 | Donma Hsu Design.