Skip to content

Commit a50ea06

Browse files
committed
Handle proxies also for ASP.NET Core
- Handle proxies in both ASP.NET and ASP.NET Core - Remove port number from IP, if it is contained (Azure includes in X-Forwarded-For header)
1 parent 9148495 commit a50ea06

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

src/Serilog.Enrichers.ClientInfo/Enrichers/ClientIpEnricher.cs

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using Serilog.Core;
22
using Serilog.Events;
3+
using System;
4+
using System.Linq;
35

46
#if NETFULL
57

@@ -49,9 +51,7 @@ private string GetIpAddress()
4951

5052
if (!string.IsNullOrEmpty(ipAddress))
5153
{
52-
var addresses = ipAddress.Split(',');
53-
if (addresses.Length != 0)
54-
return addresses[0];
54+
return GetIpAddressFromProxy(ipAddress);
5555
}
5656

5757
return _contextAccessor.HttpContext.Request.ServerVariables["REMOTE_ADDR"];
@@ -60,8 +60,31 @@ private string GetIpAddress()
6060
#else
6161
private string GetIpAddress()
6262
{
63-
return _contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
63+
var ipAddress = _contextAccessor.HttpContext.Request.Headers["X-forwarded-for"].FirstOrDefault();
64+
65+
if (!string.IsNullOrEmpty(ipAddress))
66+
{
67+
return GetIpAddressFromProxy(ipAddress);
68+
}
69+
70+
return _contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
6471
}
6572
#endif
73+
74+
private string GetIpAddressFromProxy(string proxiedIpList)
75+
{
76+
var addresses = proxiedIpList.Split(',');
77+
78+
if (addresses.Length != 0)
79+
{
80+
// If IP contains port, it will be after the last : (IPv6 uses : as delimiter and could have more of them)
81+
return addresses[0].Contains(":")
82+
? addresses[0].Substring(0, addresses[0].LastIndexOf(":", StringComparison.Ordinal))
83+
: addresses[0];
84+
}
85+
86+
return string.Empty;
87+
}
88+
6689
}
67-
}
90+
}

0 commit comments

Comments
 (0)