Skip to content

Commit

Permalink
😊 新增 获取客户端 IPv4 支持配置是否优先获取请求头携带的 X-Forwarded-For
Browse files Browse the repository at this point in the history
  • Loading branch information
MonkSoul committed Jun 25, 2024
1 parent 89ce2f1 commit c280dfd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,19 @@ public static string GetLocalIpAddressToIPv6(this HttpContext context)
/// 获取远程 IPv4地址
/// </summary>
/// <param name="context"></param>
/// <param name="xff">是否优先取 X-Forwarded-For</param>
/// <returns></returns>
public static string GetRemoteIpAddressToIPv4(this HttpContext context)
public static string GetRemoteIpAddressToIPv4(this HttpContext context, bool xff = false)
{
return context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString();
var ipv4 = context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString();

if (xff)
{
var xForwardedFor = context.Request.Headers["X-Forwarded-For"];
return !string.IsNullOrWhiteSpace(xForwardedFor) ? xForwardedFor : ipv4;
}

return ipv4;
}

/// <summary>
Expand Down
13 changes: 11 additions & 2 deletions framework/Furion/AspNetCore/Extensions/HttpContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,19 @@ public static string GetLocalIpAddressToIPv6(this HttpContext context)
/// 获取远程 IPv4地址
/// </summary>
/// <param name="context"></param>
/// <param name="xff">是否优先取 X-Forwarded-For</param>
/// <returns></returns>
public static string GetRemoteIpAddressToIPv4(this HttpContext context)
public static string GetRemoteIpAddressToIPv4(this HttpContext context, bool xff = false)
{
return context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString();
var ipv4 = context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString();

if (xff)
{
var xForwardedFor = context.Request.Headers["X-Forwarded-For"];
return !string.IsNullOrWhiteSpace(xForwardedFor) ? xForwardedFor : ipv4;
}

return ipv4;
}

/// <summary>
Expand Down

0 comments on commit c280dfd

Please sign in to comment.