备忘asp.net core使用中间件实现IP白名单访问

1、**添加中间件MiddleWare**

 1  public class MyMiddleware
 2     {
 3         private readonly RequestDelegate _next;
 4         private readonly ILogger<MyMiddleware> _logger;
 5         private readonly string _safelist;
 6         public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger, string safelist)
 7         {
 8             _safelist = safelist;
 9             _next = next;
10             _logger = logger;
11         }
12         public async Task Invoke(HttpContext context)
13         {
14             var remoteIp = context.Connection.RemoteIpAddress;
15             FileStream fs = new FileStream("ip.txt", FileMode.OpenOrCreate);
16             //获得字节数组
17             byte[] data = System.Text.Encoding.Default.GetBytes(DateTime.Now + "ip" + ":" + remoteIp);
18             //开始写入
19             fs.Write(data, 0, data.Length);
20             //清空缓冲区、关闭流
21             fs.Flush();
22             fs.Close();
23             _logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
24             string[] ip = _safelist.Split(';');
25             var bytes = remoteIp.GetAddressBytes(); var badIp = true;
26             for (int i = 0; i < ip.Length; i++)
27 
28             {
29                 var testIp = IPAddress.Parse(ip[i]);
30                 if (testIp.GetAddressBytes().SequenceEqual(bytes))
31                 { badIp = false; break; }
32             }
33             if (badIp)
34             {
35                 _logger.LogWarning($"Forbidden Request from Remote IP address: {remoteIp}");
36                 context.Response.StatusCode = StatusCodes.Status403Forbidden;
37                 await context.Response.WriteAsync($"Forbidden Request from Remote IP address: {remoteIp}");
38 
39                 return;
40             }
41             await _next.Invoke(context);
42         }
43     }

2.**在statr up中使用中间件(可以将IP地址放在appsetting.json中多个ip使用";"分隔)** 

 1 app.UseMiddleware(Configuration["WhiteIPList"]); 

 

posted @ 2021-05-24 11:01  Wilson_it  阅读(325)  评论(0编辑  收藏  举报