chenhaozhe
2026-11-10 44cfd3ebcd8fc8cce27df9d0c66b12de92979b5c
网关添加 扩展名过滤,响应页面拦截器。
避免 DLL 文件,日志文件泄露。
4个文件已修改
3个文件已添加
749 ■■■■■ 已修改文件
.gitignore 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Filter/FileExtensionFilter.cs 118 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Filter/InternalHostSet.cs 46 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Filter/UpstreamErrorPageFilter.cs 553 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Program.cs 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Properties/PublishProfiles/FolderProfile1.pubxml.user 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
appsettings.json 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.gitignore
@@ -64,3 +64,5 @@
*.coverage
coverage*.xml
coverage*.json
.trash/
Filter/FileExtensionFilter.cs
New file
@@ -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,不转发到后端。
    /// 说明:这是请求管道中间件(middleware),而不是 YARP 的 IProxyConfigFilter,
    /// 因为配置过滤器只能改写 Route/Cluster 配置,无法直接产生 HTTP 响应。
    /// 配置节:Gateway:FileFilter:Enabled(默认 true)、Gateway: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>();
    }
}
Filter/InternalHostSet.cs
New file
@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
namespace APIGetway.Filter
{
    /// <summary>
    /// 计算"内部地址"主机集合:回环地址 + 所有 YARP 后端目的地主机 + 配置中额外声明的主机。
    /// 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;
        }
    }
}
Filter/UpstreamErrorPageFilter.cs
New file
@@ -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) 后端(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);
        }
    }
}
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(需在静态文件与反向代理之前)
app.UseFileExtensionFilter();
app.UseUpstreamErrorPageFilter();
app.UseDefaultFiles();
app.UseStaticFiles();
// YARP 转发:匹配 /API_NW/ 前缀的请求转发到后端
// YARP 转发:按 appsettings.json 中的 Routes 规则转发到后端
app.MapReverseProxy();
app.Run();
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>
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"
          }
        }
      }