diff --git a/src/InterfaceForward.Api/InterfaceForwardApiModule.cs b/src/InterfaceForward.Api/InterfaceForwardApiModule.cs index be6e567..2dd50b3 100644 --- a/src/InterfaceForward.Api/InterfaceForwardApiModule.cs +++ b/src/InterfaceForward.Api/InterfaceForwardApiModule.cs @@ -75,11 +75,12 @@ public class InterfaceForwardApiModule : FakeModule }); }); - //Nginx代理的话获取真实IP services.Configure(options => { - options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; - //新增如下两行 + // 反向代理场景下恢复客户端真实来源信息,供 Swagger、鉴权和重定向等中间件使用 + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | + ForwardedHeaders.XForwardedProto | + ForwardedHeaders.XForwardedHost; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); }); @@ -94,6 +95,9 @@ public class InterfaceForwardApiModule : FakeModule { var app = context.GetWebApplication(); + // 必须在读取 Scheme/Host/PathBase 的中间件之前执行,否则 Swagger 会生成错误的请求地址 + app.UseForwardedHeaders(); + app.Use(async (httpContext, next) => { httpContext.Request.EnableBuffering(); @@ -118,8 +122,6 @@ public class InterfaceForwardApiModule : FakeModule app.UseAuthentication(); app.UseAuthorization(); - app.UseForwardedHeaders();//Nginx代理的话获取真实IP - app.MapControllers(); app.Services.GetRequiredService().Send("Application started");