mirror of
https://gitee.com/ccnetcore/Yi
synced 2026-03-03 00:00:58 +08:00
refactor: ai+人工重构优化 framework
This commit is contained in:
@@ -5,32 +5,53 @@ using Volo.Abp.AspNetCore.WebClientInfo;
|
||||
|
||||
namespace Yi.Framework.AspNetCore;
|
||||
|
||||
/// <summary>
|
||||
/// 真实IP地址提供程序,支持代理服务器场景
|
||||
/// </summary>
|
||||
public class RealIpHttpContextWebClientInfoProvider : HttpContextWebClientInfoProvider
|
||||
{
|
||||
public RealIpHttpContextWebClientInfoProvider(ILogger<HttpContextWebClientInfoProvider> logger,
|
||||
IHttpContextAccessor httpContextAccessor) : base(logger, httpContextAccessor)
|
||||
private const string XForwardedForHeader = "X-Forwarded-For";
|
||||
|
||||
/// <summary>
|
||||
/// 初始化真实IP地址提供程序的新实例
|
||||
/// </summary>
|
||||
public RealIpHttpContextWebClientInfoProvider(
|
||||
ILogger<HttpContextWebClientInfoProvider> logger,
|
||||
IHttpContextAccessor httpContextAccessor)
|
||||
: base(logger, httpContextAccessor)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取客户端IP地址,优先从X-Forwarded-For头部获取
|
||||
/// </summary>
|
||||
/// <returns>客户端IP地址</returns>
|
||||
protected override string? GetClientIpAddress()
|
||||
{
|
||||
try
|
||||
{
|
||||
var httpContext = HttpContextAccessor.HttpContext;
|
||||
|
||||
var headers = httpContext?.Request?.Headers;
|
||||
|
||||
if (headers != null && headers.ContainsKey("X-Forwarded-For"))
|
||||
if (httpContext == null)
|
||||
{
|
||||
httpContext.Connection.RemoteIpAddress =
|
||||
IPAddress.Parse(headers["X-Forwarded-For"].FirstOrDefault());
|
||||
return null;
|
||||
}
|
||||
|
||||
return httpContext?.Connection?.RemoteIpAddress?.ToString();
|
||||
var headers = httpContext.Request?.Headers;
|
||||
if (headers != null && headers.ContainsKey(XForwardedForHeader))
|
||||
{
|
||||
// 从X-Forwarded-For获取真实客户端IP
|
||||
var forwardedIp = headers[XForwardedForHeader].FirstOrDefault();
|
||||
if (!string.IsNullOrEmpty(forwardedIp))
|
||||
{
|
||||
httpContext.Connection.RemoteIpAddress = IPAddress.Parse(forwardedIp);
|
||||
}
|
||||
}
|
||||
|
||||
return httpContext.Connection?.RemoteIpAddress?.ToString();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogException(ex, LogLevel.Warning);
|
||||
Logger.LogWarning(ex, "获取客户端IP地址时发生异常");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user