- 在ASP.NET CORE应用程序的Startup.cs文件中,通过添加以下代码调用中间件来启用请求跟踪:
app.UseForwardedHeaders();
app.Use(async (context, next) =>
{
var forwardedHeaders = context.Request.Headers["X-Forwarded-For"];
if (!string.IsNullOrEmpty(forwardedHeaders))
{
var forwardedIps = forwardedHeaders.ToString().Split(",");
context.Connection.RemoteIpAddress = IPAddress.Parse(forwardedIps[0]);
}
await next.Invoke();
});
- 现在,在控制器或视图中,您可以访问客户端IP地址作为context.Connection.RemoteIpAddress属性的值。
public IActionResult Index()
{
var ipAddress = HttpContext.Connection.RemoteIpAddress;
return View();
}