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 { /// /// 统一处理 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,相对程序目录)。 /// 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 _logger; private readonly IConfiguration _configuration; public UpstreamErrorPageFilter(RequestDelegate next, ILogger logger, IConfiguration configuration) { _next = next; _logger = logger; _configuration = configuration; } public async Task InvokeAsync(HttpContext context) { if (!_configuration.GetValue(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; } } /// /// 读取页面配置节中的 标记信息。如果配置节中没有指定标记信息,则使用模块中默认的标记信息 /// /// /// internal static string[] ResolveMarkers(IConfiguration configuration) { var list = new List(); 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; } /// 按状态码生成与请求地址无关的中性提示页。 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 "" + "" + "" + title + "" + "" + "
" + "
" + statusCode + "
" + "

" + title + "

" + "

" + hint + "

" + "
"; } } /// /// 原始错误页归档:把被替换掉的响应体写到 PageLogs 目录,文件名形如 20261110-162012-345_404_ab12cd34.log。 /// 后缀故意用 .log —— 既表明它是日志,又能被 FileExtensionFilter 一并拦截,避免归档内容被再次下载。 /// 任何写入异常都只记日志,绝不影响发往客户端的响应。 /// 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(Section + ":" + EnabledKey, true); var configured = configuration.GetValue(Section + ":" + DirectoryKey); var directory = string.IsNullOrWhiteSpace(configured) ? "PageLogs" : configured.Trim(); _directory = Path.IsPathRooted(directory) ? directory : Path.Combine(AppContext.BaseDirectory, directory); } /// 保存原始响应体,返回落盘路径;未保存时返回 null。 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; } } /// 错误页可能被 IIS/Kestrel 压缩,落盘前尽量还原成可读的 HTML;失败则保留原始字节。 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 { /// /// 注册"错误详情/错误页统一处理",需放在 MapReverseProxy 之前才会覆盖代理响应。 /// public static IApplicationBuilder UseUpstreamErrorPageFilter(this IApplicationBuilder app) => app.UseMiddleware(); } /// /// 响应体包装:遇到 4xx/5xx 的 HTML 响应时先缓存一小段内容, /// 判断是不是"服务器错误详情页",是则整段换成中性提示,否则原样写出。 /// 其它响应(正常内容、JSON、文件下载)直接透传,不做缓存。 /// 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); } /// /// 读取配置节中的 InternalHosts(网关内部地址),用于判断错误页中是否包含内部地址,避免泄露给客户端。 /// /// /// private static string[] BuildInternalHosts(IConfiguration configuration) { var hosts = InternalHostSet.Build(configuration, "Gateway:ErrorPage", "InternalHosts"); var list = new List(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(buffer, offset, count), CancellationToken.None).GetAwaiter().GetResult(); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => WriteCoreAsync(new ReadOnlyMemory(buffer, offset, count), cancellationToken); public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => new(WriteCoreAsync(buffer, cancellationToken)); private async Task WriteCoreAsync(ReadOnlyMemory 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); } } /// 响应结束时的兜底处理。 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(); } } /// 网关自己产生的 4xx/5xx(未匹配路由、后端不可达)通常是空响应体,补一个中性提示页。 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; } /// /// 4xx/5xx 的 HTML 响应先整段缓存(最多 MaxInspectBytes),等响应结束再判断是否替换, /// 这样归档到 PageLogs 的原始页面是完整的,而不是只捕获到前半段。 /// 超过缓存上限时不再等待整页,按已捕获内容判断,避免大响应长期占用内存。 /// 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); } /// 错误页被压缩时无法按文本匹配特征词,统一按"错误页"处理(等整段收完再替换)。 private bool IsCompressed() => _response.Headers.ContentEncoding.Count > 0; /// 0 = 直接透传,1 = 需要按文本检查内容,2 = 压缩过的错误页(无法按文本检查,整段收完后替换)。 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); } } }