chenhaozhe
2026-11-11 4837024d8cd40e31bb4b95cbeec0ae473dfca4e3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
 
namespace APIGetway.Filter
{
    public class FolderFilter
    {
        // 配置节:Gateway:FolderFilter:Enabled(默认 true)、Gateway:FolderFilter:BlockedFolders(数组,覆盖默认值)。
        private const string Section = "Gateway:FolderFilter";
        private const string ExtensionsKey = "BlockedFolders";
 
        // 默认拦截的文件夹名(忽略大小写),不允许访问 bin、obj、vlog、dll 等编译输出目录,也不允许访问上级目录。
        private static readonly Dictionary<string, int> DefaultFolders = new Dictionary<string, int>
        {
            ["bin"] = 1,
            ["obj"] = 1,
            ["vlog"] = 1,
            ["dll"] = 1,
        };
 
 
        private readonly RequestDelegate _next;
 
        private readonly ILogger<FileExtensionFilter> _logger;
 
        private readonly bool _enabled;
 
        private readonly Dictionary<string, int> _folders;
 
        public FolderFilter(RequestDelegate next, ILogger<FileExtensionFilter> logger, IConfiguration configuration)
        {
            _next = next;
            _logger = logger;
            _enabled = configuration.GetValue<bool>($"{Section}:Enabled");
            _folders = ResolveFolders(configuration);
        }
 
        public Task InvokeAsync(HttpContext context)
        {
            if (_enabled)
            {
                var folder = MatchFolders(context.Request.Path);
                if (folder != null)
                {
                    _logger.LogWarning("已拦截 {Folder} 文件夹访问: {Method} {Path},来源 {RemoteIp}",
                        folder,
                        context.Request.Method,
                        context.Request.Path.Value,
                        context.Connection.RemoteIpAddress);
                    context.Response.StatusCode = StatusCodes.Status404NotFound;
                    return Task.CompletedTask;
                }
            }
            return _next(context);
        }
 
        private static Dictionary<string, int> ResolveFolders(IConfiguration configuration)
        {
            var folders = new Dictionary<string, int>();
            foreach (var item in configuration.GetSection(Section).GetSection(ExtensionsKey).GetChildren())
            {
                var value = item.Key?.Trim();
                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }
 
                folders[value] = 1;
            }
 
            return folders.Count > 0 ? folders : DefaultFolders;
        }
 
        
        public string? MatchFolders(PathString path)
        {
            if(!path.HasValue)
            {
                return null;
            }
 
            //var segments = path.Value.Split('/', StringSplitOptions.RemoveEmptyEntries);
 
            //if(segments.Length == 0)
            //{
            //    return null;
            //}
            //foreach (var segment in segments)
            //{
 
            //    if(_folders.TryGetValue(segment.ToLower(), out _))
            //    {
            //        return segment;
            //    }
            //}
 
            // 使用 ReadOnlySpan<char> 替代 Split 方案
            ReadOnlySpan<char> pathSpan = path.Value.AsSpan();
 
            while(!pathSpan.IsEmpty)
            {
                int slashIndex = pathSpan.IndexOf('/');
 
                // 取当前路径片段;没有斜杠时,剩余的部分就是最后一个片段
                ReadOnlySpan<char> segment = slashIndex >= 0 ?
                    pathSpan[..slashIndex] : pathSpan;
 
                // 检查当前片段是否在拦截列表中(忽略大小写)
                if (!segment.IsEmpty)
                {
                    // 直接通过字段key判断 当前路径是否在字典中,如果在字典中,则认为是敏感文件夹,返回该文件夹名称。无需判断字典Key的值,因为字典的值只是占位符。
                    // 默认字典key 取小写路径。分割的片段全部需要按照小写处理
                    if(_folders.ContainsKey(segment.ToString().ToLowerInvariant()))
                    {
                        return segment.ToString();
                    }
                }
 
                if (slashIndex < 0)
                {
                    break; // 没有更多的斜杠,结束循环
                }
 
                pathSpan = pathSpan[(slashIndex + 1)..]; // 移动到下一个片段
            }
 
            return null;
        }
    }
 
   
 
 
    public static class FolderFilterExtensions
    {
        /// <summary>
        /// 注册文件路径拦截。必须放在 UseStaticFiles / MapReverseProxy 之前。
        /// </summary>
        public static IApplicationBuilder UseFolderFilter(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<FolderFilter>();
        }
    }
}