using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
using AgileConfig.Client;
using Dpz.Core.Hangfire;
using Dpz.Core.Infrastructure.Configuration;
using Dpz.Core.Infrastructure.RateLimiting;
using Dpz.Core.Service.Mcp;
using Dpz.Core.WebApi.OpenApi;
using Dpz.Core.WebApi.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.RateLimiting;
using ModelContextProtocol.AspNetCore;
using Scalar.AspNetCore;
const string originsName = "Open";
const string openApiCachePolicyName = "openapi";
Log.Logger = new LoggerConfiguration().Enrich.FromLogContext().CreateBootstrapLogger();
try
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseAgileConfig(new ConfigClient(builder.Configuration));
// 开发环境下重新加载本地配置,覆盖配置中心的特定节点
if (builder.Environment.IsDevelopment())
{
builder.Configuration.AddJsonFile(
"appsettings.Development.json",
optional: true,
reloadOnChange: true
);
}
var configuration = builder.Configuration;
var seq = configuration.GetSection("LogSeq").Get<LogSeq>();
builder.Host.ConfigurationLog(seq);
#region services
var services = builder.Services;
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
});
services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter(
"comment",
opt =>
{
opt.AutoReplenishment = true;
opt.PermitLimit = 3;
opt.Window = TimeSpan.FromMinutes(1);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 2;
}
);
options.AddFixedWindowLimiter(
"callback",
opt =>
{
opt.AutoReplenishment = true;
opt.PermitLimit = 60;
opt.Window = TimeSpan.FromMinutes(1);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 2;
}
);
// 仅 /mcp 端点使用的独立限流策略(60次/分钟),与 comment/callback 等业务限流互不相干
options.AddFixedWindowLimiter(
McpApiKeyDefaults.RateLimitPolicyName,
opt =>
{
opt.AutoReplenishment = true;
opt.PermitLimit = 60;
opt.Window = TimeSpan.FromMinutes(1);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 2;
}
);
});
services
.AddControllers()
// .AddXmlDataContractSerializerFormatters()
//.AddXmlSerializerFormatters()
.AddMessagePackSerializerFormatters()
.AddJsonOptions(opts =>
{
opts.JsonSerializerOptions.Converters.Add(new TimeSpanConverter());
opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
services.AddResponseCompression(options =>
{
// 显式 Providers 会覆盖框架默认的 zstd → brotli → gzip,需自行补上 Zstandard;
// 注册顺序即 q 值相同时的优先级,zstd 在前,不支持的客户端回退 brotli / gzip
options.Providers.Add<ZstandardCompressionProvider>();
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat([
"application/font-woff2",
"image/svg+xml",
"text/plain",
"application/lrc",
]);
// HTTPS 请求默认不压缩:本地开发直连 https,以及生产由反代终止 TLS 后
// 经 ForwardedHeaders 还原的 https 都会命中该判断,不开这个开关就永远没有 Content-Encoding
options.EnableForHttps = true;
});
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
services.Configure<ZstandardCompressionProviderOptions>(options =>
{
options.CompressionOptions = new ZstandardCompressionOptions { Quality = 6 };
});
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = int.MaxValue;
});
services.AddEndpointsApiExplorer();
services.AddOutputCache(options =>
{
// 仅 /openapi/v1.json 使用;不设基策略,避免缓存全部 GET 端点
options.AddPolicy(openApiCachePolicyName, policy => policy.Expire(TimeSpan.FromDays(7)));
});
services.AddOpenApi(options =>
{
options.AddDocumentTransformer<OpenApiDocumentTransformer>();
});
// IoC
services.AddBusinessServices(configuration);
services.AddIpRateLimit(configuration);
services.AddDefaultServices().AddProjectServices().AddMessageQueueServices(configuration);
// Cors
services.AddCors(options =>
{
options.AddPolicy(
originsName,
cfg =>
{
/*
* 可以使用:
* cfg.SetIsOriginAllowed(origin =>
* (configuration.GetSection("Origins").Get<string[]>() ?? [])
* .Contains(origin, StringComparer.OrdinalIgnoreCase)
* )
* 内部实时读取 Origins,配合 AgileConfig/配置文件热更新即可免重启生效
* 该委托在每次经过请求时都会执行
*
*/
var origins = configuration.GetSection("Origins").Get<string[]>() ?? [];
cfg.WithOrigins(origins)
.WithMethods("GET", "PUT", "POST", "DELETE", "PATCH")
.AllowAnyHeader();
}
);
});
// ---- 认证方案边界 ----
// AddAuthentication(JwtBearer) 保持 JwtBearer 为默认方案,因此所有不带 AuthenticationSchemes 的
// 默认 [Authorize] 接口(含 Permissions 权限策略)依旧只走 JWT 认证,新增方案不会改变它们的行为。
// McpApiKey 只是"候选方案",不会被默认使用;只有下方 McpApiKey 策略(仅挂在 /mcp)显式
// AddAuthenticationSchemes 后,请求才会触发 McpApiKeyAuthenticationHandler。
var issuer = configuration["Server:Issuer"] ?? throw new InvalidConfigurationException();
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = issuer;
options.Audience = "resource_server";
options.RequireHttpsMetadata = true;
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Log.Error(context.Exception, "Failed to authenticate");
return Task.CompletedTask;
},
};
})
// 注意:该 handler 会把 Authorization: Bearer 后的一段也当作 MCP 密钥来比对,
// 但它只在 /mcp 的策略里被启用,不会劫持任何默认 JWT 接口
.AddScheme<AuthenticationSchemeOptions, McpApiKeyAuthenticationHandler>(
McpApiKeyDefaults.AuthenticationScheme,
_ => { }
);
// 注册授权策略:Permissions 枚举逐个建策略(默认走 JWT)+ 追加只认 McpApiKey 方案的
// "McpApiKey" 策略(供 /mcp 使用)。默认接口的权限策略均未绑定认证方案,认证仍用默认 JwtBearer。
services.AddPermissionAuthorization();
// MCP HTTP 服务端: WithHttpTransport 提供 /mcp 端点(无状态会话);
// 每次工具调用经 DI(ActivatorUtilities)按请求作用域现造目标实例,构造参数里的 scoped 服务可正常注入。
services
.AddMcpServer()
.WithHttpTransport(options =>
{
options.SessionMode = HttpServerSessionMode.Stateless;
})
.WithMyTools();
services.AddRazorPages();
var webApiHangfireCollectionPrefix =
configuration["WebApiHangfireCollectionPrefix"]
?? throw new InvalidConfigurationException();
services.AddHangfireService(configuration, webApiHangfireCollectionPrefix);
#endregion
var app = builder.Build();
#region configuration
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseForwardedHeaders();
app.UseSerilogRequestLogging(options =>
{
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
diagnosticContext.Set(
"UserAgent",
httpContext.Request.Headers["User-Agent"].ToString()
);
diagnosticContext.Set("IpAddress", httpContext.Request.GetIpAddress());
};
});
app.UseCurrentUserRequiredExceptionHandling();
app.UseResponseHeaders().UseRequestRecord().UseDateTimeLocalFormat();
app.UseResponseCompression();
app.MapOpenApi().CacheOutput(openApiCachePolicyName);
app.MapScalarApiReference(options =>
{
options.Title = "Dpz.Core.WebApi";
options.Favicon = "https://dpangzi.com/favicon.ico";
options.Theme = ScalarTheme.Saturn;
options.HideDarkModeToggle = false;
options.HideClientButton = true;
});
// //强制HTTPS
// app.UseHttpsRedirection();
app.UseRouting();
app.MapRazorPages();
app.UseCors(originsName);
//身份认证
app.UseAuthentication();
//身份授权
app.UseAuthorization();
//输出缓存:须在 UseRouting/UseCors/UseAuthentication/UseAuthorization 之后
app.UseOutputCache();
app.UseRateLimiter();
app.MapControllers();
//app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
#if DEBUG
app.HangfireSetting();
#endif
// 未配置 MCP 密钥时整个 /mcp 不上线,避免留下无意义的探测面
var mcpApiKey = configuration[McpApiKeyDefaults.ConfigurationKey];
if (string.IsNullOrWhiteSpace(mcpApiKey))
{
Log.Warning("Mcp:ApiKey is not configured; HTTP MCP endpoint will not be mapped");
}
else
{
// 边界:该端点只接受 X-Mcp-Api-Key(或 Authorization: Bearer <MCP密钥>),
// 策略把认证锁定在 McpApiKey 方案 —— 即使用户携带合法 JWT 也会被拒绝(401),与业务接口互不相通
app.MapMcp("/mcp")
.RequireAuthorization(McpApiKeyDefaults.PolicyName)
.RequireRateLimiting(McpApiKeyDefaults.RateLimitPolicyName);
}
#endregion
app.MapGet("/ping", () => "pong");
app.MapGet(
"/datetime",
() => $"{DateTime.Now:yyyy/Mm/dd HH:mm:ss}\r\n{Environment.MachineName}"
);
app.UseDevToolsEndpoint();
app.UseVersionEndpoint();
Log.Information("Starting web api host,current process id:{ID}", Environment.ProcessId);
app.Run();
}
catch (Exception e)
{
Console.Error.WriteLine(e);
Log.Fatal(e, "Host terminated unexpectedly");
}
/// <summary>
///
/// </summary>
public partial class Program
{
/// <summary>
/// 身份认证Cookie名称
/// </summary>
public const string AuthorizeCookieName = "Dpz.Web.Api.Server.Authoriza";
/// <summary>
/// 账号Cookie名称
/// </summary>
public const string AccountCookieName = "Dpz.Web.Api.Server.Account";
}
⚠⚠ 以下内容为AI分析的结果,请根据实际情况进行判断。
一句话定位
Dpz.Core.WebApi/Program.cs 是对外 REST API 宿主(资源服务器)的唯一组合根:顶部用 top-level statements 串起「引导日志 → AgileConfig 配置 → 服务注册 → 中间件管道 → 端点映射」,末尾留下一个只承载两个 Cookie 名称常量的 partial class Program。
关键内容与边界
启动骨架
Log.Logger先建 bootstrap logger,整个流程包在try/catch,失败时Console.Error+Log.Fatal。但全文件没有Log.CloseAndFlush():进程被docker stop/正常退出时,Seq 与WriteTo.Async缓冲里的最后一批日志可能丢失。- 配置源顺序是
UseAgileConfig(new ConfigClient(builder.Configuration))→ 开发环境再AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true),后注册者胜出,所以本地文件能覆盖配置中心同名节点。该文件optional: true,且项目目录下没有 appsettings 文件(csproj里有UserSecretsId),本地引导配置到底来自 user secrets 还是环境变量,未确认。 builder.Host.ConfigurationLog(seq)转交 LogConfiguration.cs:LogSeq缺失、ServerUri/Program(非 DEBUG 还要ApiKey)为空都直接抛ArgumentNullException——日志配置不全不是降级到控制台,而是启动即崩。另外 Dpz.Core.WebApi/README.md 的示例写的是ServerUrl,实际属性是ServerUri,照 README 配会直接启动失败。
限流:三份策略、没有分区键
comment(3/分)、callback(60/分)、mcp(60/分,策略名取自 McpApiKeyDefaults.cs 的RateLimitPolicyName) 结构逐字重复。- 都调用
AddFixedWindowLimiter(name, ...)且没有指定分区,配额是整个进程共享的,不是按 IP 或用户计价。comment策略同时挂在 CommentController.cs 与 EmailVerifyController.cs 上,意味着任意一个客户端耗尽后,全站发评论/发验证码都会一起被卡;QueueLimit = 2+OldestFirst还会让超限请求排队等待而不是立刻拒绝。 - 未设
RejectionStatusCode/OnRejected,被限流时按框架默认返回 503 而非 429。
响应压缩
- 显式
Providers.Add会整体覆盖框架默认的 zstd → brotli → gzip 顺序,因此手动补了ZstandardCompressionProvider,顺序即优先级。ZstandardCompressionProvider/ZstandardCompressionProviderOptions在本仓库源码中没有定义(全局 using 提供了Microsoft.AspNetCore.ResponseCompression/System.IO.Compression,随 net11.0 目标框架提供),其选项语义只能对照 Dpz.Core.Web/Program.cs 的同款写法,仓库内无实现可核对。 EnableForHttps = true是刻意打开的,注释说明反代终止 TLS 后经 ForwardedHeaders 还原的 https 也会命中该判断——这一段注释与实现一致,不要随手删。services.Configure<KestrelServerOptions>(MaxRequestBodySize = int.MaxValue)与下面清空KnownProxies/KnownIPNetworks叠加后,上传面基本没有防护(见「需要注意的点」)。
CORS
Origins在策略构建时读取一次,改配置必须重启;注释里给出的SetIsOriginAllowed实时读取方案没有采用。Origins缺失时WithOrigins([])只是「不允许任何跨域来源」,不报错也不告警。
认证/授权边界(注释本身就是契约)
- 默认方案仍是
JwtBearer:Authority = Server:Issuer(缺失即抛InvalidConfigurationException,类型见 InvalidConfigurationException.cs)、Audience = "resource_server"、RequireHttpsMetadata = true;OnAuthenticationFailed把异常写Log.Error——token 过期这类常态失败也会按 Error 落盘。 McpApiKey只是候选方案:只有 PermissionAuthorizationExtensions.cs 里McpApiKey策略显式AddAuthenticationSchemes才会触发 McpApiKeyAuthenticationHandler.cs。该 handler 会把Authorization: Bearer xxx里的 xxx 当作 MCP 密钥比对,即 JWT 头与 API Key 头共用一个位置;一旦有人把这个策略误挂到业务端点上,携带合法 JWT 的请求会因密钥比对失败直接 401。handler 每次请求读配置(Mcp:ApiKey),用固定时间比较,挑战/禁止时只写状态码、不写WWW-Authenticate。AddPermissionAuthorization()为每个非 0Permissions值建同名策略,判定在 PermissionHandler.cs:每个受保护请求都await currentUserService.GetUserInfoAsync(),取不到用户或权限位不含要求就Fail()(不是「跳过」,所以不允许匿名放行)。
MCP 端点
AddMcpServer().WithHttpTransport(Stateless).WithMyTools():WithMyTools()在 McpServiceExtensions.cs 里反射扫描[McpServerToolType],工具类不进 DI,每次tools/call由 SDK 用ActivatorUtilities按请求作用域现造,所以构造函数参数必须能从 scoped 容器解析。/mcp映射是启动期决定:Mcp:ApiKey为空就整段不上线,只打一条 Warning。这与 handler 每请求读配置不对称——运行中用 AgileConfig 把密钥从空改成有值,端点不会自动上线,必须重启;排「/mcp 404」先看启动日志。
Hangfire
WebApiHangfireCollectionPrefix缺失直接抛异常,但 HangfireExtensions.cs 在ConnectionStrings:hangfireMongodb缺失时是静默return。于是 DEBUG 构建下app.HangfireSetting()仍会UseHangfireDashboard("/jobs"),存储未注册时面板会怎样(报错还是空面板)未实测,但两处对缺失配置的态度不一致这一点是确定的。该面板IsReadOnlyFunc = _ => false,可编辑任务,仅#if DEBUG暴露。HangfireSetting()里还顺带UseRequestLocalization(zh-CN),所以 Release 构建没有请求本地化。
其他
AddOutputCache只有openapi一条策略(7 天),刻意不设基策略;MapOpenApi().CacheOutput(...)在开发环境同样生效,改了控制器后文档可能长时间不刷新(缓存在进程内,多实例各自独立)。MapScalarApiReference与MapOpenApi没有IsDevelopment包裹,生产同样暴露/openapi/*与/scalar/*。GET /ping、GET /datetime是给外部监控对时用的;/datetime的格式串"yyyy/Mm/dd HH:mm:ss"是笔误(Mm把月份和分钟拼在一起),仓库其他位置统一用yyyy/MM/dd。- Release 构建没有统一异常处理中间件(开发环境是
UseDeveloperExceptionPage),除CurrentUserRequiredException被特判为 401 外,其他异常直接落到 Kestrel 500。
依赖与协作
- 服务注册全部走扩展方法:
AddBusinessServices(ServiceExtensions.cs,含 Redis 连接、仓储、FusionCache、幂等锁)、AddDefaultServices(ServiceDependencyInjection.cs,源生成器驱动的领域服务)、AddProjectServices/AddMessageQueueServices/HangfireSetting(DependencyInjectionExtensions.cs)、AddIpRateLimit(RateLimitMiddlewareExtensions.cs)、UseResponseHeaders/UseRequestRecord/UseDateTimeLocalFormat/AddMessagePackSerializerFormatters(ToolsExtensions.cs)、UseDevToolsEndpoint/UseVersionEndpoint(AspNetCoreServiceCollectionExtensions.cs)。 - 大量类型靠 Imports.cs 的 global using 落地(
Permissions、InvalidConfigurationException、GetIpAddress()、LogSeq、MVC/压缩相关命名空间等),读这段代码时不要以为缺 using。 AddMessageQueueServices会为每个消息类型注册RabbitMQConsumerBackgroundService后台服务(见 MessageQueueServiceExtensions.cs),即 API 宿主本身也在消费 MQ,与 Jobs 宿主构成竞争消费。- 消费本文件注册物的位置:
comment/callback在 CommentController.cs、EmailVerifyController.cs、SysController.cs 的EnableRateLimiting中;IIpRateLimitService只在 BlacklistController.cs 被注入用于黑名单管理。
流程与时序
flowchart TD
A["UseDeveloperExceptionPage (仅 Dev)"] --> B["UseForwardedHeaders<br/>KnownIPNetworks/KnownProxies 已清空"]
B --> C["UseSerilogRequestLogging<br/>注入 Host/Scheme/UA/IpAddress"]
C --> D["UseCurrentUserRequiredExceptionHandling<br/>CurrentUserRequiredException → 401"]
D --> E["UseResponseHeaders<br/>Expose-Headers:*,401 补 WWW-Authenticate"]
E --> F["UseRequestRecord<br/>QueryString + ≤1KB 请求体写入日志"]
F --> G["UseDateTimeLocalFormat<br/>(仅 ?date_format=zh-cn/zh-date 生效)"]
G --> H["UseResponseCompression"]
H --> I["MapOpenApi(7 天输出缓存) / MapScalarApiReference / MapRazorPages"]
I --> J["UseRouting → UseCors(Open) → UseAuthentication → UseAuthorization"]
J --> K["UseOutputCache → UseRateLimiter"]
K --> L["MapControllers"]
L --> M{"Mcp:ApiKey 非空?"}
M -- 否 --> N["仅 Warning,/mcp 不映射"]
M -- 是 --> O["MapMcp('/mcp')<br/>McpApiKey 策略 + mcp 限流"]
N --> P["/ping、/datetime、devtools、api/version"]
O --> P
顺序上有两处真实的强依赖:UseSerilogRequestLogging 必须在 UseRequestRecord 之前(HttpRequestRecord.cs 依赖 IDiagnosticContext 注水);UseOutputCache 在 UseRateLimiter 之前,命中缓存的响应会绕过限流。
需要注意的点
- 限流没有分区键是本文件最实在的设计漏洞:
comment的 3 次/分是全局额度,一个客户端就能让全站发评论/发验证码 503,和「防刷」的初衷相反;三份策略也只差数字,重复度高。 - 伪造来源没有门槛:
KnownIPNetworks/KnownProxies全清空 + ApplicationTools.cs 的GetIpAddress优先信任Ali-Cdn-Real-Ip、再X-Forwarded-For(取第一个)、再X-Real-IP,任何客户端直连都能伪造日志里的IpAddress与RequestScheme;叠加MaxRequestBodySize = int.MaxValue、本宿主没有UseIpRateLimit()(只有 Auth/Web 宿主有),WebApi 在上传与来源维度基本裸奔。 - DEBUG 构建会把 IP 写死:
GetIpAddress()在#if DEBUG下直接return "113.110.235.52",本地调试出来的请求日志 IP 全是这一个值。 - 请求体进日志:
HttpRequestRecord把 query 和最多 1KB 的 body 注入 Serilog(同时写文件与 Seq),登录、回调等载荷一起落盘;而且它在管道开头就把 body 预读到 1KB 或读完,慢速大请求会在这里被拖住。 DateTimeFormattingMiddleware会整包缓冲响应:只在带?date_format=zh-cn|zh-date且非/export时生效,GetStream+ 全量 JSON 重写,大响应成本明显;其catch只记日志、finally恢复Response.Body,格式化失败时下游已写入的内容不会回滚给客户端。- 文档面暴露:
/openapi/*、/scalar/*不区分环境,OpenAPI 文档还被缓存 7 天(含开发环境),改接口后需要重启才刷新。 - MCP 的 401 会被改写成 Bearer 语义:
HttpResponseHeaderHandel对任何 401 都补WWW-Authenticate: Bearer realm="api",/mcp的密钥校验失败也会带上这条头,而 handler 自己刻意不写WWW-Authenticate,两者意图相抵。 - 末尾
public partial class Program的两个常量在本仓库内没有任何使用点:AuthorizeCookieName只出现在本文件与生成的 Dpz.Core.WebApi.xml,真正使用 Cookie 名的是 Dpz.Core.Web/Program.cs 自己那套(Dpz.Web.Core.Authoriza),全仓库也没有WebApplicationFactory<Program>。目前它只是历史遗留的集成测试锚点;保留partial class Program本身(供外部测试程序集引用宿主)仍是有意义的,但两个常量是死代码。 - 本文件的一段注释(认证方案边界、OutputCache 放置位置、
SetIsOriginAllowed备选方案、限流策略互不相干、压缩 provider 覆盖默认)属于维护约束:改管道顺序或改策略挂载点时应当逐条核对,尤其是别把McpApiKey策略挂到业务端点上。
AI 正在分析代码…
评论加载中...