From 44cfd3ebcd8fc8cce27df9d0c66b12de92979b5c Mon Sep 17 00:00:00 2001
From: chenhaozhe <cgz@hz-kingdee.com>
Date: 星期二, 10 十一月 2026 17:08:22 +0800
Subject: [PATCH] 网关添加 扩展名过滤,响应页面拦截器。 避免 DLL 文件,日志文件泄露。
---
Filter/FileExtensionFilter.cs | 118 +++++++++
appsettings.json | 17 +
.gitignore | 2
Properties/PublishProfiles/FolderProfile1.pubxml.user | 2
Program.cs | 11
Filter/InternalHostSet.cs | 46 +++
Filter/UpstreamErrorPageFilter.cs | 553 ++++++++++++++++++++++++++++++++++++++++++
7 files changed, 743 insertions(+), 6 deletions(-)
diff --git a/.gitignore b/.gitignore
index e841b15..8b7d2c4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -64,3 +64,5 @@
*.coverage
coverage*.xml
coverage*.json
+
+.trash/
diff --git a/Filter/FileExtensionFilter.cs b/Filter/FileExtensionFilter.cs
new file mode 100644
index 0000000..0e68e94
--- /dev/null
+++ b/Filter/FileExtensionFilter.cs
@@ -0,0 +1,118 @@
+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
+{
+ /// <summary>
+ /// 閫氱敤鏂囦欢鍚庣紑鎷︽埅锛氬懡涓厤缃殑鍚庣紑锛堥粯璁� .dll銆�.log锛夋椂鐩存帴杩斿洖 406 Not Acceptable锛屼笉杞彂鍒板悗绔��
+ /// 璇存槑锛氳繖鏄姹傜閬撲腑闂翠欢锛坢iddleware锛夛紝鑰屼笉鏄� YARP 鐨� IProxyConfigFilter锛�
+ /// 鍥犱负閰嶇疆杩囨护鍣ㄥ彧鑳芥敼鍐� Route/Cluster 閰嶇疆锛屾棤娉曠洿鎺ヤ骇鐢� HTTP 鍝嶅簲銆�
+ /// 閰嶇疆鑺傦細Gateway:FileFilter:Enabled锛堥粯璁� true锛夈�丟ateway:FileFilter:BlockedExtensions锛堟暟缁勶紝瑕嗙洊榛樿鍊硷級銆�
+ /// </summary>
+ public class FileExtensionFilter
+ {
+ private const string Section = "Gateway:FileFilter";
+ private const string ExtensionsKey = "BlockedExtensions";
+
+ private static readonly string[] DefaultExtensions = { ".dll", ".log" };
+
+ private readonly RequestDelegate _next;
+ private readonly ILogger<FileExtensionFilter> _logger;
+ private readonly bool _enabled;
+ private readonly string[] _extensions;
+
+ public FileExtensionFilter(RequestDelegate next, ILogger<FileExtensionFilter> logger, IConfiguration configuration)
+ {
+ _next = next;
+ _logger = logger;
+ _enabled = configuration.GetValue<bool>(Section + ":Enabled", true);
+ _extensions = ResolveExtensions(configuration);
+ }
+
+ public Task InvokeAsync(HttpContext context)
+ {
+ if (_enabled)
+ {
+ var extension = MatchExtension(context.Request.Path);
+ if (extension != null)
+ {
+ _logger.LogWarning("宸叉嫤鎴� {Extension} 鏂囦欢璁块棶: {Method} {Path}锛屾潵婧� {RemoteIp}",
+ extension,
+ context.Request.Method,
+ context.Request.Path.Value,
+ context.Connection.RemoteIpAddress);
+
+ context.Response.StatusCode = StatusCodes.Status404NotFound;
+ return Task.CompletedTask;
+ }
+ }
+
+ return _next(context);
+ }
+
+ /// <summary>璇诲彇閰嶇疆鐨勫悗缂�鍒楄〃锛堢粺涓�琛ュ墠瀵肩偣銆佸拷鐣ュぇ灏忓啓锛夛紝鏈厤缃垯鐢ㄩ粯璁ゅ�笺��</summary>
+ private static string[] ResolveExtensions(IConfiguration configuration)
+ {
+ var list = new List<string>();
+ foreach (var item in configuration.GetSection(Section).GetSection(ExtensionsKey).GetChildren())
+ {
+ var value = item.Value?.Trim();
+ if (string.IsNullOrEmpty(value))
+ {
+ continue;
+ }
+
+ if (!value.StartsWith(".", StringComparison.Ordinal))
+ {
+ value = "." + value;
+ }
+
+ list.Add(value);
+ }
+
+ return list.Count > 0 ? list.ToArray() : DefaultExtensions;
+ }
+
+ /// <summary>鍙栬矾寰勬渶鍚庝竴娈靛苟鍖归厤鍚庣紑锛堝拷鐣ュぇ灏忓啓锛屽吋瀹圭粨灏炬枩鏉狅級銆�</summary>
+ private string? MatchExtension(PathString path)
+ {
+ if (!path.HasValue)
+ {
+ return null;
+ }
+
+ var value = path.Value!.TrimEnd('/');
+ if (value.Length == 0)
+ {
+ return null;
+ }
+
+ var lastSlash = value.LastIndexOf('/');
+ var fileName = lastSlash >= 0 ? value[(lastSlash + 1)..] : value;
+
+ foreach (var extension in _extensions)
+ {
+ if (fileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
+ {
+ return extension;
+ }
+ }
+
+ return null;
+ }
+ }
+
+ public static class FileExtensionFilterExtensions
+ {
+ /// <summary>
+ /// 娉ㄥ唽鏂囦欢鍚庣紑鎷︽埅銆傚繀椤绘斁鍦� UseStaticFiles / MapReverseProxy 涔嬪墠銆�
+ /// </summary>
+ public static IApplicationBuilder UseFileExtensionFilter(this IApplicationBuilder app)
+ => app.UseMiddleware<FileExtensionFilter>();
+ }
+}
diff --git a/Filter/InternalHostSet.cs b/Filter/InternalHostSet.cs
new file mode 100644
index 0000000..3e5f753
--- /dev/null
+++ b/Filter/InternalHostSet.cs
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using Microsoft.Extensions.Configuration;
+
+namespace APIGetway.Filter
+{
+ /// <summary>
+ /// 璁$畻"鍐呴儴鍦板潃"涓绘満闆嗗悎锛氬洖鐜湴鍧� + 鎵�鏈� YARP 鍚庣鐩殑鍦颁富鏈� + 閰嶇疆涓澶栧0鏄庣殑涓绘満銆�
+ /// LocationRewriteFilter 涓� UpstreamErrorPageFilter 鍏辩敤銆�
+ /// </summary>
+ internal static class InternalHostSet
+ {
+ private static readonly string[] LoopbackHosts =
+ {
+ "localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"
+ };
+
+ internal static HashSet<string> Build(IConfiguration configuration, string extraSection, string extraKey)
+ {
+ var comparer = StringComparer.OrdinalIgnoreCase;
+ var hosts = new HashSet<string>(LoopbackHosts, comparer);
+
+ foreach (var cluster in configuration.GetSection("ReverseProxy:Clusters").GetChildren())
+ {
+ foreach (var destination in cluster.GetSection("Destinations").GetChildren())
+ {
+ var address = destination["Address"];
+ if (Uri.TryCreate(address, UriKind.Absolute, out var uri) && !string.IsNullOrEmpty(uri.Host))
+ {
+ hosts.Add(uri.Host);
+ }
+ }
+ }
+
+ foreach (var extra in configuration.GetSection(extraSection).GetSection(extraKey).GetChildren())
+ {
+ if (!string.IsNullOrWhiteSpace(extra.Value))
+ {
+ hosts.Add(extra.Value.Trim());
+ }
+ }
+
+ return hosts;
+ }
+ }
+}
diff --git a/Filter/UpstreamErrorPageFilter.cs b/Filter/UpstreamErrorPageFilter.cs
new file mode 100644
index 0000000..3f31b1a
--- /dev/null
+++ b/Filter/UpstreamErrorPageFilter.cs
@@ -0,0 +1,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) 鍚庣锛圛IS/ASP.NET锛夌殑璇︾粏閿欒椤典細鎶婂唴閮ㄥ湴鍧�锛坔ttp://localhost:81/...锛夊拰鏈嶅姟鍣�
+ /// 鐗╃悊璺緞锛團:\\缃戠珯鍙戝竷\\...锛夌洿鎺ュ啓杩� HTML锛岀粡缃戝叧閫忎紶灏辨毚闇茬粰浜嗘祻瑙堝櫒锛�
+ /// 2) 缃戝叧鑷韩锛圷ARP 鏈尮閰嶈矾鐢便�佸悗绔笉鍙揪锛夎繑鍥炵殑閿欒鍝嶅簲閫氬父鏄┖鍝嶅簲浣撱��
+ /// 杩欓噷瀵�"鐘舵�佺爜 >= 400 涓� Content-Type 涓� text/html锛堟垨娌℃湁鍝嶅簲浣擄級"鐨勫搷搴斿仛澶勭悊锛�
+ /// 鍛戒腑閿欒璇︽儏鐗瑰緛鏃舵妸鍐呭鎹㈡垚涓庡湴鍧�鏃犲叧鐨勪腑鎬ф彁绀猴紝绌哄搷搴斾綋鍒欒ˉ涓�涓腑鎬ф彁绀洪〉銆�
+ /// 鍏跺畠鍝嶅簲锛堟甯稿唴瀹广�丣SON 鎺ュ彛閿欒銆佹枃浠朵笅杞斤級鍘熸牱閫忎紶銆�
+ /// 瑙﹀彂鏇挎崲鏃讹紝鍘熷閿欒椤典細鍏堝啓鍏� 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 = "璇锋鏌ヨ闂湴鍧�鏄惁姝g‘銆�";
+ }
+ 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>
+ /// 鍘熷閿欒椤靛綊妗o細鎶婅鏇挎崲鎺夌殑鍝嶅簲浣撳啓鍒� 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("宸插綊妗e師濮嬮敊璇〉锛歿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 涔嬪墠鎵嶄細瑕嗙洊浠g悊鍝嶅簲銆�
+ /// </summary>
+ public static IApplicationBuilder UseUpstreamErrorPageFilter(this IApplicationBuilder app)
+ => app.UseMiddleware<UpstreamErrorPageFilter>();
+ }
+
+ /// <summary>
+ /// 鍝嶅簲浣撳寘瑁咃細閬囧埌 4xx/5xx 鐨� HTML 鍝嶅簲鏃跺厛缂撳瓨涓�灏忔鍐呭锛�
+ /// 鍒ゆ柇鏄笉鏄�"鏈嶅姟鍣ㄩ敊璇鎯呴〉"锛屾槸鍒欐暣娈垫崲鎴愪腑鎬ф彁绀猴紝鍚﹀垯鍘熸牱鍐欏嚭銆�
+ /// 鍏跺畠鍝嶅簲锛堟甯稿唴瀹广�丣SON銆佹枃浠朵笅杞斤級鐩存帴閫忎紶锛屼笉鍋氱紦瀛樸��
+ /// </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;
+
+ // 鏇挎崲涔嬪墠鍏堟妸鍘熷閿欒椤电暀妗o紙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);
+ }
+ }
+}
diff --git a/Program.cs b/Program.cs
index 17319e1..e16352d 100644
--- a/Program.cs
+++ b/Program.cs
@@ -1,9 +1,11 @@
using Microsoft.Extensions.Hosting.WindowsServices;
+using APIGetway.Filter;
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
- ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : null
+ // IIS 杩涚▼鍐呮墭绠℃椂宸ヤ綔鐩綍涓嶆槸绔欑偣鐩綍锛屽浐瀹氫负绋嬪簭鐩綍鎵嶈兘璇诲埌 appsettings.json
+ ContentRootPath = AppContext.BaseDirectory
});
builder.Services.AddWindowsService(options => options.ServiceName = "APIGetway");
@@ -14,10 +16,15 @@
var app = builder.Build();
+// 鎷︽埅瀵� DLL/LOG 绛夋晱鎰熷悗缂�鐨勮闂紝鐩存帴杩斿洖 406锛堥渶鍦ㄩ潤鎬佹枃浠朵笌鍙嶅悜浠g悊涔嬪墠锛�
+app.UseFileExtensionFilter();
+
+app.UseUpstreamErrorPageFilter();
+
app.UseDefaultFiles();
app.UseStaticFiles();
-// YARP 杞彂锛氬尮閰� /API_NW/ 鍓嶇紑鐨勮姹傝浆鍙戝埌鍚庣
+// YARP 杞彂锛氭寜 appsettings.json 涓殑 Routes 瑙勫垯杞彂鍒板悗绔�
app.MapReverseProxy();
app.Run();
diff --git a/Properties/PublishProfiles/FolderProfile1.pubxml.user b/Properties/PublishProfiles/FolderProfile1.pubxml.user
index 19aa989..274ea5a 100644
--- a/Properties/PublishProfiles/FolderProfile1.pubxml.user
+++ b/Properties/PublishProfiles/FolderProfile1.pubxml.user
@@ -3,7 +3,7 @@
<Project>
<PropertyGroup>
<_PublishTargetUrl>F:\缃戠珯鍙戝竷\APIGateway</_PublishTargetUrl>
- <History>True|2026-11-09T01:50:20.3651906Z||;</History>
+ <History>True|2026-11-10T08:34:30.1187375Z||;True|2026-11-10T16:28:40.4045409+08:00||;False|2026-11-10T16:28:37.3348136+08:00||;True|2026-11-10T16:27:44.5323533+08:00||;True|2026-11-10T16:26:20.7674970+08:00||;True|2026-11-10T15:47:59.7843377+08:00||;False|2026-11-10T15:46:07.7669474+08:00||;False|2026-11-10T15:46:05.2442797+08:00||;False|2026-11-10T15:46:03.3664927+08:00||;False|2026-11-10T15:45:47.6003342+08:00||;True|2026-11-10T14:26:32.9989135+08:00||;True|2026-11-10T14:07:58.8871076+08:00||;False|2026-11-10T14:07:22.8184692+08:00||;False|2026-11-10T14:06:47.1047518+08:00||;True|2026-11-09T09:50:20.3651906+08:00||;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>
\ No newline at end of file
diff --git a/appsettings.json b/appsettings.json
index 6e9de47..a13e719 100644
--- a/appsettings.json
+++ b/appsettings.json
@@ -6,15 +6,26 @@
}
},
"AllowedHosts": "*",
+ "Gateway": {
+ "FileFilter": {
+ "Enabled": true,
+ "BlockedExtensions": [ ".dll", ".log" ]
+ },
+ "ErrorPage": {
+ "Enabled": true,
+ "LogPageEnabled": true,
+ "LogPageDirectory": "PageLogs"
+ }
+ },
"ReverseProxy": {
"Routes": {
"mes-backend": {
"ClusterId": "mes-backend",
"Match": {
- "Path": "/API_NW/{**catch-all}"
+ "Path": "/API/{**catch-all}"
},
"Transforms": [
- { "PathRemovePrefix": "/API_NW" }
+ //{ "PathRemovePrefix": "/API" }
]
}
},
@@ -22,7 +33,7 @@
"mes-backend": {
"Destinations": {
"backend": {
- "Address": "http://localhost:8090"
+ "Address": "http://localhost:81"
}
}
}
--
Gitblit v1.9.1