如何在Azure Functions中获取客户端IP,对应Flask request.remote_addr功能
Azure Functions 读取客户端IP实现方法
Azure 平台会默认将原始客户端IP注入到HTTP请求的X-Forwarded-For请求头中,不需要额外做服务端配置,直接读取解析该头即可实现和PHP的$_SERVER['REMOTE_ADDR']、Flask的request.remote_addr同等效果。
Python 语言实现示例
import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: # 读取X-Forwarded-For头,格式为 客户端IP:端口,代理1IP:端口,代理2IP:端口 forwarded_ip = req.headers.get("X-Forwarded-For", "") client_ip = "" if forwarded_ip: # 提取第一个IP并去除端口部分 client_ip = forwarded_ip.split(",")[0].split(":")[0].strip() # 本地调试场景回退方案 else: client_ip = req.headers.get("Remote-Addr", "127.0.0.1") # 此处添加你的业务逻辑 return func.HttpResponse(f"客户端IP: {client_ip}")
C# 语言实现示例
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using System.Linq; public static class GetClientIpFunction { [FunctionName("GetClientIp")] public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log) { string clientIp = string.Empty; if (req.Headers.TryGetValue("X-Forwarded-For", out var forwardedHeaders)) { clientIp = forwardedHeaders.FirstOrDefault()?.Split(',').First().Split(':').First().Trim() ?? string.Empty; } // 本地调试回退读取连接IP if (string.IsNullOrEmpty(clientIp)) { clientIp = req.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "127.0.0.1"; } return new OkObjectResult(new { ClientIp = clientIp }); } }
注意事项
- 如果你的Azure Static Web App额外配置了CDN、WAF等中间代理层,需要确认代理层已开启
X-Forwarded-For头透传,避免获取到代理节点的IP而非真实客户端IP - 本地调试时获取到的IP为127.0.0.1属于正常现象,部署到Azure生产环境后会自动注入真实客户端IP
- 上述方案兼容IPv4和IPv6地址格式
内容的提问来源于stack exchange,提问作者Joe Platano
相关产品推荐
相关产品推荐

