1
chenhaozhe
2026-11-11 e8e5bda49946c89411f2231c2466c10597a7c7fc
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
 
namespace APIGetway.Filter
{
    /// <summary>
    /// 统一处理 4xx/5xx 的错误响应:
    /// 1) 后端(IIS/ASP.NET)的详细错误页会把内部地址(http://localhost:81/...)和服务器
    ///    物理路径(F:\\网站发布\\...)直接写进 HTML,经网关透传就暴露给了浏览器;
    /// 2) 网关自身(YARP 未匹配路由、后端不可达)返回的错误响应通常是空响应体。
    /// 这里对"状态码 >= 400 且 Content-Type 为 text/html(或没有响应体)"的响应做处理:
    /// 命中错误详情特征时把内容换成与地址无关的中性提示,空响应体则补一个中性提示页。
    /// 其它响应(正常内容、JSON 接口错误、文件下载)原样透传。
    /// 触发替换时,原始错误页会先写入 PageLogs 目录(后缀 .log)供维护人员排查;
    /// 该后缀同时被 FileExtensionFilter 拦截,无法通过网关直接访问到。
    /// 配置节:Gateway:ErrorPage:Enabled(默认 true)/ Gateway:ErrorPage:Markers(自定义特征词)/
    ///         Gateway:ErrorPage:LogPageEnabled(默认 true)/ Gateway:ErrorPage:LogPageDirectory(默认 PageLogs,相对程序目录)。
    /// </summary>
    public class UpstreamErrorPageFilter
    {
        private const string Section = "Gateway:ErrorPage";
        private const string MarkersKey = "Markers";
 
        private static readonly string[] DefaultMarkers =
        {
            "详细错误", "Detailed Error Information", "HTTP 错误", "HTTP Error",
            "请求的 URL", "Requested URL", "物理路径", "Physical Path",
            "StackTrace", "Exception Details", "server error in", "服务器错误"
        };
 
        private readonly RequestDelegate _next;
        private readonly ILogger<UpstreamErrorPageFilter> _logger;
        private readonly IConfiguration _configuration;
 
        public UpstreamErrorPageFilter(RequestDelegate next, ILogger<UpstreamErrorPageFilter> logger, IConfiguration configuration)
        {
            _next = next;
            _logger = logger;
            _configuration = configuration;
        }
 
        public async Task InvokeAsync(HttpContext context)
        {
            if (!_configuration.GetValue<bool>(Section + ":Enabled", true))
            {
                await _next(context);
                return;
            }
 
            var originalBody = context.Response.Body;
            var archive = new PageArchive(_configuration, _logger);
            var wrapper = new ErrorPageBodyWrapper(context.Response, originalBody, _configuration, _logger, archive);
            context.Response.Body = wrapper;
 
            try
            {
                await _next(context);
            }
            finally
            {
                await wrapper.FinishAsync();
                context.Response.Body = originalBody;
            }
        }
        /// <summary>
        /// 读取页面配置节中的 标记信息。如果配置节中没有指定标记信息,则使用模块中默认的标记信息
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        internal static string[] ResolveMarkers(IConfiguration configuration)
        {
            var list = new List<string>();
            foreach (var item in configuration.GetSection(Section).GetSection(MarkersKey).GetChildren())
            {
                if (!string.IsNullOrWhiteSpace(item.Value))
                {
                    list.Add(item.Value.Trim());
                }
            }
 
            return list.Count > 0 ? list.ToArray() : DefaultMarkers;
        }
 
        /// <summary>按状态码生成与请求地址无关的中性提示页。</summary>
        internal static string BuildHtml(int statusCode)
        {
            string title;
            string hint;
 
            if (statusCode == StatusCodes.Status404NotFound)
            {
                title = "页面不存在";
                hint = "请检查访问地址是否正确。";
            }
            else if (statusCode >= StatusCodes.Status500InternalServerError)
            {
                title = "服务暂时不可用";
                hint = "请稍后重试,或联系管理员。";
            }
            else
            {
                title = "请求无法处理";
                hint = "请检查访问方式是否正确。";
            }
 
            return "<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\" />" +
                   "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />" +
                   "<title>" + title + "</title></head>" +
                   "<body style=\"margin:0;font-family:system-ui,-apple-system,'Microsoft YaHei',sans-serif;" +
                   "display:flex;align-items:center;justify-content:center;min-height:100vh;color:#333;background:#f7f8fa\">" +
                   "<div style=\"text-align:center;padding:24px\">" +
                   "<div style=\"font-size:56px;font-weight:700;color:#c9ced8;line-height:1.1\">" + statusCode + "</div>" +
                   "<h1 style=\"font-size:20px;font-weight:600;margin:12px 0 8px\">" + title + "</h1>" +
                   "<p style=\"color:#8a91a0;margin:0;font-size:14px\">" + hint + "</p>" +
                   "</div></body></html>";
        }
    }
 
    /// <summary>
    /// 原始错误页归档:把被替换掉的响应体写到 PageLogs 目录,文件名形如 20261110-162012-345_404_ab12cd34.log。
    /// 后缀故意用 .log —— 既表明它是日志,又能被 FileExtensionFilter 一并拦截,避免归档内容被再次下载。
    /// 任何写入异常都只记日志,绝不影响发往客户端的响应。
    /// </summary>
    internal sealed class PageArchive
    {
        private const string Section = "Gateway:ErrorPage";
        private const string EnabledKey = "LogPageEnabled";
        private const string DirectoryKey = "LogPageDirectory";
 
        private readonly bool _enabled;
        private readonly string _directory;
        private readonly ILogger _logger;
 
        public PageArchive(IConfiguration configuration, ILogger logger)
        {
            _logger = logger;
            _enabled = configuration.GetValue<bool>(Section + ":" + EnabledKey, true);
 
            var configured = configuration.GetValue<string>(Section + ":" + DirectoryKey);
            var directory = string.IsNullOrWhiteSpace(configured) ? "PageLogs" : configured.Trim();
            _directory = Path.IsPathRooted(directory) ? directory : Path.Combine(AppContext.BaseDirectory, directory);
        }
 
        /// <summary>保存原始响应体,返回落盘路径;未保存时返回 null。</summary>
        public string? Save(byte[] content, HttpResponse response)
        {
            if (!_enabled || content.Length == 0)
            {
                return null;
            }
 
            try
            {
                Directory.CreateDirectory(_directory);
 
                var fileName = string.Format(
                    "{0:yyyyMMdd-HHmmss-fff}_{1}_{2}.log",
                    DateTime.Now,
                    response.StatusCode,
                    Guid.NewGuid().ToString("N").Substring(0, 8));
 
                var path = Path.Combine(_directory, fileName);
                var decoded = Decode(content, response.Headers.ContentEncoding.ToString());
                File.WriteAllBytes(path, decoded ?? content);
 
                _logger.LogInformation("已归档原始错误页:{FilePath}({Length} 字节,状态 {StatusCode},请求 {RequestPath})",
                    path,
                    (decoded ?? content).Length,
                    response.StatusCode,
                    response.HttpContext.Request.Path.Value);
 
                return path;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "归档原始错误页失败:{RequestPath}", response.HttpContext.Request.Path.Value);
                return null;
            }
        }
 
        /// <summary>错误页可能被 IIS/Kestrel 压缩,落盘前尽量还原成可读的 HTML;失败则保留原始字节。</summary>
        private static byte[]? Decode(byte[] content, string? contentEncoding)
        {
            if (string.IsNullOrWhiteSpace(contentEncoding))
            {
                return null;
            }
 
            try
            {
                using var input = new MemoryStream(content);
                using var output = new MemoryStream();
 
                switch (contentEncoding.ToLowerInvariant())
                {
                    case "gzip":
                        using (var decoder = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
                        {
                            decoder.CopyTo(output);
                        }
 
                        return output.ToArray();
                    case "deflate":
                        using (var decoder = new System.IO.Compression.ZLibStream(input, System.IO.Compression.CompressionMode.Decompress))
                        {
                            decoder.CopyTo(output);
                        }
 
                        return output.ToArray();
                    case "br":
                        using (var decoder = new System.IO.Compression.BrotliStream(input, System.IO.Compression.CompressionMode.Decompress))
                        {
                            decoder.CopyTo(output);
                        }
 
                        return output.ToArray();
                    default:
                        return null;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
 
    public static class UpstreamErrorPageFilterExtensions
    {
        /// <summary>
        /// 注册"错误详情/错误页统一处理",需放在 MapReverseProxy 之前才会覆盖代理响应。
        /// </summary>
        public static IApplicationBuilder UseUpstreamErrorPageFilter(this IApplicationBuilder app)
            => app.UseMiddleware<UpstreamErrorPageFilter>();
    }
 
    /// <summary>
    /// 响应体包装:遇到 4xx/5xx 的 HTML 响应时先缓存一小段内容,
    /// 判断是不是"服务器错误详情页",是则整段换成中性提示,否则原样写出。
    /// 其它响应(正常内容、JSON、文件下载)直接透传,不做缓存。
    /// </summary>
    internal sealed class ErrorPageBodyWrapper : Stream
    {
        private enum State
        {
            Unknown,
            Inspecting,
            PassThrough,
            Replaced
        }
 
        private const int MaxInspectBytes = 64 * 1024;
 
        private readonly HttpResponse _response;
        private readonly Stream _inner;
        private readonly ILogger _logger;
        private readonly PageArchive _archive;
        private readonly string[] _markers;
        private readonly string[] _internalHosts;
        private readonly MemoryStream _pending = new();
 
        private State _state = State.Unknown;
 
        public ErrorPageBodyWrapper(HttpResponse response, Stream inner, IConfiguration configuration, ILogger logger, PageArchive archive)
        {
            _response = response;
            _inner = inner;
            _logger = logger;
            _archive = archive;
            _markers = UpstreamErrorPageFilter.ResolveMarkers(configuration);
            _internalHosts = BuildInternalHosts(configuration);
        }
 
        /// <summary>
        /// 读取配置节中的 InternalHosts(网关内部地址),用于判断错误页中是否包含内部地址,避免泄露给客户端。
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        private static string[] BuildInternalHosts(IConfiguration configuration)
        {
            var hosts = InternalHostSet.Build(configuration, "Gateway:ErrorPage", "InternalHosts");
            var list = new List<string>(hosts.Count);
            foreach (var host in hosts)
            {
                if (!string.IsNullOrWhiteSpace(host))
                {
                    list.Add(host);
                }
            }
 
            return list.ToArray();
        }
 
        public override bool CanRead => false;
        public override bool CanSeek => false;
        public override bool CanWrite => true;
        public override long Length => throw new NotSupportedException();
        public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
        public override void Flush() => FlushAsync(CancellationToken.None).GetAwaiter().GetResult();
        public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
        public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
        public override void SetLength(long value) => throw new NotSupportedException();
 
        public override void Write(byte[] buffer, int offset, int count)
            => WriteCoreAsync(new ReadOnlyMemory<byte>(buffer, offset, count), CancellationToken.None).GetAwaiter().GetResult();
 
        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            => WriteCoreAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
 
        public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
            => new(WriteCoreAsync(buffer, cancellationToken));
 
        private async Task WriteCoreAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
        {
            switch (_state)
            {
                case State.Replaced:
                    return;
                case State.PassThrough:
                    await _inner.WriteAsync(buffer, cancellationToken);
                    return;
                case State.Unknown:
                    var mode = InspectMode();
                    if (mode == 0)
                    {
                        _state = State.PassThrough;
                        await _inner.WriteAsync(buffer, cancellationToken);
                        return;
                    }
 
                    _state = State.Inspecting;
                    _pending.Write(buffer.Span);
                    await InspectPendingAsync(cancellationToken);
                    return;
                default:
                    _pending.Write(buffer.Span);
                    await InspectPendingAsync(cancellationToken);
                    return;
            }
        }
 
        public override async Task FlushAsync(CancellationToken cancellationToken)
        {
            if (_state == State.Inspecting)
            {
                // 已经开始往客户端刷数据,无法再整体替换:把已缓存内容原样写出
                _state = State.PassThrough;
                await FlushPendingAsync(cancellationToken);
            }
 
            if (_state == State.PassThrough)
            {
                await _inner.FlushAsync(cancellationToken);
            }
        }
 
        /// <summary>响应结束时的兜底处理。</summary>
        public async Task FinishAsync()
        {
            if (_state == State.Inspecting)
            {
                if (HasSensitiveContent() || IsCompressed())
                {
                    await ReplaceAsync(CancellationToken.None);
                }
                else
                {
                    _state = State.PassThrough;
                    await FlushPendingAsync(CancellationToken.None);
                }
 
                return;
            }
 
            if (_state == State.Unknown || _state == State.PassThrough)
            {
                await FillEmptyErrorBodyAsync();
            }
        }
 
        /// <summary>网关自己产生的 4xx/5xx(未匹配路由、后端不可达)通常是空响应体,补一个中性提示页。</summary>
        private async Task FillEmptyErrorBodyAsync()
        {
            if (_response.HasStarted || _pending.Length > 0)
            {
                return;
            }
 
            if (_response.StatusCode < StatusCodes.Status400BadRequest)
            {
                return;
            }
 
            if (HttpMethods.IsHead(_response.HttpContext.Request.Method))
            {
                return;
            }
 
            var contentType = _response.ContentType;
            if (!string.IsNullOrEmpty(contentType) &&
                !contentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
 
            if (!WantsHtml())
            {
                return;
            }
 
            await ReplaceAsync(CancellationToken.None);
        }
 
        private bool WantsHtml()
        {
            var accept = _response.HttpContext.Request.Headers.Accept.ToString();
            if (string.IsNullOrWhiteSpace(accept))
            {
                return true;
            }
 
            return accept.IndexOf("text/html", StringComparison.OrdinalIgnoreCase) >= 0 ||
                   accept.IndexOf("application/xhtml", StringComparison.OrdinalIgnoreCase) >= 0;
        }
 
        /// <summary>
        /// 4xx/5xx 的 HTML 响应先整段缓存(最多 MaxInspectBytes),等响应结束再判断是否替换,
        /// 这样归档到 PageLogs 的原始页面是完整的,而不是只捕获到前半段。
        /// 超过缓存上限时不再等待整页,按已捕获内容判断,避免大响应长期占用内存。
        /// </summary>
        private Task InspectPendingAsync(CancellationToken cancellationToken)
        {
            if (_response.HasStarted)
            {
                _state = State.PassThrough;
                return FlushPendingAsync(cancellationToken);
            }
 
            if (_pending.Length <= MaxInspectBytes)
            {
                return Task.CompletedTask;
            }
 
            if (HasSensitiveContent() || IsCompressed())
            {
                return ReplaceAsync(cancellationToken);
            }
 
            _state = State.PassThrough;
            return FlushPendingAsync(cancellationToken);
        }
 
        /// <summary>错误页被压缩时无法按文本匹配特征词,统一按"错误页"处理(等整段收完再替换)。</summary>
        private bool IsCompressed() => _response.Headers.ContentEncoding.Count > 0;
 
        /// <summary>0 = 直接透传,1 = 需要按文本检查内容,2 = 压缩过的错误页(无法按文本检查,整段收完后替换)。</summary>
        private int InspectMode()
        {
            if (_response.StatusCode < StatusCodes.Status400BadRequest)
            {
                return 0;
            }
 
            var contentType = _response.ContentType;
            if (contentType == null || !contentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase))
            {
                return 0;
            }
 
            if (_response.Headers.ContainsKey("Content-Encoding"))
            {
                return 2;
            }
 
            if (_response.ContentLength.HasValue && _response.ContentLength.Value > MaxInspectBytes)
            {
                return 0;
            }
 
            return 1;
        }
 
        private bool HasSensitiveContent()
        {
            if (_pending.Length == 0)
            {
                return false;
            }
 
            var text = Encoding.UTF8.GetString(_pending.GetBuffer(), 0, (int)_pending.Length);
 
            foreach (var marker in _markers)
            {
                if (text.IndexOf(marker, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    return true;
                }
            }
 
            foreach (var host in _internalHosts)
            {
                if (text.IndexOf(host, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    return true;
                }
            }
 
            return false;
        }
 
        private async Task ReplaceAsync(CancellationToken cancellationToken)
        {
            _state = State.Replaced;
 
            // 替换之前先把原始错误页留档(PageLogs 目录,后缀 .log),供维护人员对照排查
            _archive.Save(_pending.ToArray(), _response);
 
            var bytes = Encoding.UTF8.GetBytes(UpstreamErrorPageFilter.BuildHtml(_response.StatusCode));
 
            if (!_response.HasStarted)
            {
                _response.Headers.Remove("Content-Encoding");
                _response.ContentLength = bytes.Length;
                _response.ContentType = "text/html; charset=utf-8";
            }
 
            _logger.LogDebug("已用中性错误页替换:{Method} {Path} 返回 {StatusCode}",
                _response.HttpContext.Request.Method, _response.HttpContext.Request.Path.Value, _response.StatusCode);
 
            await _inner.WriteAsync(bytes, cancellationToken);
        }
 
        private async Task FlushPendingAsync(CancellationToken cancellationToken)
        {
            if (_pending.Length == 0)
            {
                return;
            }
 
            var bytes = _pending.ToArray();
            _pending.SetLength(0);
            await _inner.WriteAsync(bytes, cancellationToken);
        }
    }
}