1
1
using Microsoft . AspNetCore . Http ;
2
2
using Microsoft . Extensions . DependencyInjection ;
3
+ using Microsoft . Extensions . Primitives ;
3
4
using Sentry . Internal . Extensions ;
4
5
5
6
namespace Sentry . AspNetCore ;
@@ -98,13 +99,8 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
98
99
Method = HttpMethod . Post ,
99
100
Content = new StreamContent ( memoryStream ) ,
100
101
} ;
101
- var existingForwardedFor = context . Request . Headers [ "X-Forwarded-For" ] ;
102
- var clientIp = context . Connection ? . RemoteIpAddress ? . ToString ( ) ;
103
- if ( clientIp != null )
102
+ if ( CreateXForwardedForHeader ( context ) is { } forwardedFor )
104
103
{
105
- var forwardedFor = string . IsNullOrEmpty ( existingForwardedFor )
106
- ? clientIp
107
- : $ "{ existingForwardedFor } , { clientIp } ";
108
104
sentryRequest . Headers . Add ( "X-Forwarded-For" , forwardedFor ) ;
109
105
}
110
106
var responseMessage = await client . SendAsync ( sentryRequest ) . ConfigureAwait ( false ) ;
@@ -126,6 +122,25 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
126
122
}
127
123
}
128
124
125
+ private static string ? CreateXForwardedForHeader ( HttpContext context )
126
+ {
127
+ var existingForwardedFor = context . Request . Headers [ "X-Forwarded-For" ] ;
128
+ var clientIp = context . Connection ? . RemoteIpAddress ? . ToString ( ) ;
129
+ if ( clientIp is null )
130
+ {
131
+ return existingForwardedFor . Count > 0 ? existingForwardedFor . ToString ( ) : null ;
132
+ }
133
+
134
+ if ( existingForwardedFor . Count == 0 )
135
+ {
136
+ return clientIp ;
137
+ }
138
+
139
+ return string . IsNullOrEmpty ( existingForwardedFor )
140
+ ? clientIp
141
+ : $ "{ existingForwardedFor } , { clientIp } ";
142
+ }
143
+
129
144
private bool IsHostAllowed ( string host ) =>
130
145
host . EndsWith ( ".sentry.io" , StringComparison . OrdinalIgnoreCase ) ||
131
146
host . Equals ( "sentry.io" , StringComparison . OrdinalIgnoreCase ) ||
0 commit comments