11using System ;
22using System . Net ;
33using System . Threading . Tasks ;
4- using Bing . Logs ;
54using Microsoft . AspNetCore . Builder ;
65using Microsoft . AspNetCore . Hosting ;
76using Microsoft . AspNetCore . Http ;
7+ using Microsoft . Extensions . Logging ;
88using Microsoft . Extensions . Options ;
99
1010namespace Bing . AspNetCore . RealIp
@@ -24,15 +24,22 @@ public class RealIpMiddleware : IMiddleware
2424 /// </summary>
2525 private readonly RealIpOptions _options ;
2626
27+ /// <summary>
28+ /// 日志
29+ /// </summary>
30+ private readonly ILogger < RealIpMiddleware > _logger ;
31+
2732 /// <summary>
2833 /// 初始化一个<see cref="RealIpMiddleware"/>类型的实例
2934 /// </summary>
3035 /// <param name="next">方法</param>
3136 /// <param name="options">真实IP选项</param>
32- public RealIpMiddleware ( RequestDelegate next , IOptions < RealIpOptions > options )
37+ /// <param name="logger">日志</param>
38+ public RealIpMiddleware ( RequestDelegate next , IOptions < RealIpOptions > options , ILogger < RealIpMiddleware > logger )
3339 {
3440 _next = next ;
3541 _options = options . Value ;
42+ _logger = logger ;
3643 }
3744
3845 /// <summary>
@@ -47,33 +54,17 @@ public async Task InvokeAsync(HttpContext context)
4754 if ( headers . ContainsKey ( _options . HeaderKey ) )
4855 {
4956 context . Connection . RemoteIpAddress = IPAddress . Parse (
50- _options . HeaderKey . Equals ( "x-forwarded-for" , StringComparison . CurrentCultureIgnoreCase )
57+ _options . HeaderKey . Equals ( "x-forwarded-for" , StringComparison . CurrentCultureIgnoreCase )
5158 ? headers [ "X-Forwarded-For" ] . ToString ( ) . Split ( ',' ) [ 0 ]
5259 : headers [ _options . HeaderKey ] . ToString ( ) ) ;
53-
54- WriteLog ( context , context . Connection . RemoteIpAddress ) ;
60+ _logger . LogDebug ( $ "解析真实IP成功: { context . Connection . RemoteIpAddress } ") ;
5561 }
5662 }
5763 finally
5864 {
5965 await _next ( context ) ;
6066 }
6167 }
62-
63- /// <summary>
64- /// 写入日志
65- /// </summary>
66- /// <param name="context">Http上下文</param>
67- /// <param name="address">IP地址</param>
68- private void WriteLog ( HttpContext context , IPAddress address )
69- {
70- if ( context == null )
71- return ;
72- var log = Log . GetLog ( this )
73- . Caption ( "真实IP中间件" ) ;
74- log . Content ( $ "解析真实IP成功 : { address } ")
75- . Debug ( ) ;
76- }
7768 }
7869
7970 /// <summary>
0 commit comments