2024-10-21 23:28:52 +08:00
|
|
|
|
using System.Net;
|
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
using Volo.Abp.AspNetCore.WebClientInfo;
|
|
|
|
|
|
|
|
|
|
|
|
namespace Yi.Framework.AspNetCore;
|
|
|
|
|
|
|
2025-02-23 03:06:06 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 真实IP地址提供程序,支持代理服务器场景
|
|
|
|
|
|
/// </summary>
|
2024-10-21 23:28:52 +08:00
|
|
|
|
public class RealIpHttpContextWebClientInfoProvider : HttpContextWebClientInfoProvider
|
|
|
|
|
|
{
|
2025-02-23 03:06:06 +08:00
|
|
|
|
private const string XForwardedForHeader = "X-Forwarded-For";
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 初始化真实IP地址提供程序的新实例
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public RealIpHttpContextWebClientInfoProvider(
|
|
|
|
|
|
ILogger<HttpContextWebClientInfoProvider> logger,
|
|
|
|
|
|
IHttpContextAccessor httpContextAccessor)
|
|
|
|
|
|
: base(logger, httpContextAccessor)
|
2024-10-21 23:28:52 +08:00
|
|
|
|
{
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-02-23 03:06:06 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 获取客户端IP地址,优先从X-Forwarded-For头部获取
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <returns>客户端IP地址</returns>
|
2024-10-21 23:28:52 +08:00
|
|
|
|
protected override string? GetClientIpAddress()
|
|
|
|
|
|
{
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
var httpContext = HttpContextAccessor.HttpContext;
|
2025-02-23 03:06:06 +08:00
|
|
|
|
if (httpContext == null)
|
|
|
|
|
|
{
|
|
|
|
|
|
return null;
|
|
|
|
|
|
}
|
2024-10-21 23:28:52 +08:00
|
|
|
|
|
2025-02-23 03:06:06 +08:00
|
|
|
|
var headers = httpContext.Request?.Headers;
|
|
|
|
|
|
if (headers != null && headers.ContainsKey(XForwardedForHeader))
|
2024-10-21 23:28:52 +08:00
|
|
|
|
{
|
2025-02-23 03:06:06 +08:00
|
|
|
|
// 从X-Forwarded-For获取真实客户端IP
|
|
|
|
|
|
var forwardedIp = headers[XForwardedForHeader].FirstOrDefault();
|
|
|
|
|
|
if (!string.IsNullOrEmpty(forwardedIp))
|
|
|
|
|
|
{
|
|
|
|
|
|
httpContext.Connection.RemoteIpAddress = IPAddress.Parse(forwardedIp);
|
|
|
|
|
|
}
|
2024-10-21 23:28:52 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-02-23 03:06:06 +08:00
|
|
|
|
return httpContext.Connection?.RemoteIpAddress?.ToString();
|
2024-10-21 23:28:52 +08:00
|
|
|
|
}
|
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
|
{
|
2025-02-23 03:06:06 +08:00
|
|
|
|
Logger.LogWarning(ex, "获取客户端IP地址时发生异常");
|
2024-10-21 23:28:52 +08:00
|
|
|
|
return null;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|