fix:ip显示

This commit is contained in:
xiaolipro 2025-11-03 16:49:50 +08:00
parent 0bb45537b3
commit 6ebb7870e6
2 changed files with 68 additions and 2 deletions

View File

@ -14,7 +14,7 @@ namespace InterfaceForward.Application.Filters;
public class ForwardAuthorizeFilter( public class ForwardAuthorizeFilter(
InterfaceForwardQuery interfaceForwardQuery, InterfaceForwardQuery interfaceForwardQuery,
ILogRepository logRepository, ILogRepository logRepository,
IHttpClientInfoProvider httpClientInfoProvider, NetUtil netUtil,
IBasicRepository<InterfaceEntity> interfaceRepository) IBasicRepository<InterfaceEntity> interfaceRepository)
: IAsyncActionFilter : IAsyncActionFilter
{ {
@ -28,7 +28,7 @@ public class ForwardAuthorizeFilter(
log.IsApp = true; log.IsApp = true;
log.ClientIP = httpClientInfoProvider.ClientIpAddress; log.ClientIP = netUtil.Ip;
log.Address = httpContext.Request.GetDisplayUrl(); log.Address = httpContext.Request.GetDisplayUrl();
// body // body

View File

@ -0,0 +1,66 @@
using System.Net;
using System.Net.Sockets;
using Fake.DependencyInjection;
using Microsoft.AspNetCore.Http;
namespace InterfaceForward.Application.Filters;
public class NetUtil(IHttpContextAccessor httpContextAccessor) : ITransientDependency
{
/// <summary>获取Ip</summary>
public string Ip
{
get
{
string ip = string.Empty;
if (httpContextAccessor.HttpContext != null)
ip = GetWebClientIp();
if (string.IsNullOrEmpty(ip))
ip = NetUtil.GetLanIp();
return ip;
}
}
/// <summary>得到客户端IP地址</summary>
/// <returns></returns>
private string GetWebClientIp()
{
foreach (string hostNameOrAddress in GetWebRemoteIp().Split(','))
{
foreach (IPAddress hostAddress in Dns.GetHostAddresses(hostNameOrAddress))
{
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
return hostAddress.ToString();
}
}
return string.Empty;
}
/// <summary>得到局域网IP地址</summary>
/// <returns></returns>
public static string GetLanIp()
{
foreach (IPAddress hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
return hostAddress.ToString();
}
return string.Empty;
}
/// <summary>得到远程Ip地址</summary>
/// <returns></returns>
private string GetWebRemoteIp()
{
if (httpContextAccessor.HttpContext?.Connection.RemoteIpAddress == null)
return string.Empty;
string webRemoteIp = httpContextAccessor.HttpContext?.Connection.RemoteIpAddress.ToString();
if (httpContextAccessor.HttpContext!.Request.Headers.ContainsKey("X-Real-IP"))
webRemoteIp = httpContextAccessor.HttpContext.Request.Headers["X-Real-IP"].ToString();
if (httpContextAccessor.HttpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
webRemoteIp = httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].ToString();
return webRemoteIp;
}
}