Skip to content

Commit 6fb7251

Browse files
committed
Add more null checks to get IP address.
1 parent daaf0d5 commit 6fb7251

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

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

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using Serilog.Events;
33
using System;
44
using System.Linq;
5+
using System.Runtime.CompilerServices;
56

67
#if NETFULL
78

@@ -11,6 +12,8 @@
1112
using Microsoft.AspNetCore.Http;
1213
#endif
1314

15+
[assembly: InternalsVisibleTo("Serilog.Enrichers.ClientInfo.Tests")]
16+
1417
namespace Serilog.Enrichers
1518
{
1619
public class ClientIpEnricher : ILogEventEnricher
@@ -59,25 +62,20 @@ private string GetIpAddress()
5962
{
6063
var ipAddress = _contextAccessor.HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
6164

62-
if (!string.IsNullOrEmpty(ipAddress))
63-
{
64-
return GetIpAddressFromProxy(ipAddress);
65-
}
66-
67-
return _contextAccessor.HttpContext.Request.ServerVariables["REMOTE_ADDR"];
65+
return !string.IsNullOrEmpty(ipAddress)
66+
? GetIpAddressFromProxy(ipAddress)
67+
: _contextAccessor.HttpContext.Request.ServerVariables["REMOTE_ADDR"];
6868
}
6969

7070
#else
7171
private string GetIpAddress()
7272
{
73-
var ipAddress = _contextAccessor.HttpContext.Request.Headers["X-forwarded-for"].FirstOrDefault();
73+
var ipAddress = _contextAccessor.HttpContext?.Request?.Headers["X-forwarded-for"].FirstOrDefault();
7474

7575
if (!string.IsNullOrEmpty(ipAddress))
76-
{
7776
return GetIpAddressFromProxy(ipAddress);
78-
}
7977

80-
return _contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
78+
return _contextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
8179
}
8280
#endif
8381

0 commit comments

Comments
 (0)