解决 asp.net core swagger nginx 代理转发后,添加中间路径导致swagger页面无法访问的问题 Swashbuckle
通过代理转发后,webapi的swagger无法访问,本质原因是代理后url路径发生变化导致swagger无法正常定位资源。
一般而言代理转发如果发布到网址的根路径下,不会发生这种问题,但是如果添加了中间路径,则会出现此类问题,如:
http://some-site.com/swagger => http://some-site.com/middle-path/swagger
官方文档配置:
https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-3.1#use-a-reverse-proxy-server
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
解决方法:
- 使用url相对路径
- 通过PreSerializeFilters设置根地址,并通过nginx的X-Forwarded-Prefix指定api名称
nginx配置:
server {
listen 5011;
server_name _;
location /api1/ {
proxy_pass http://192.168.56.1:5000/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host; # 使用http_host而非host以满足带有端口号的情况
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Prefix api1; # api1用于传递路由名称
}
}
Swashbuckle 5.x 以前通过PreSerializeFilters设置BasePath的方案,5.x以后,设置OpenApiServer.Url属性
代码如下:
app.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swagger, httpReq) =>
{
//根据访问地址,设置swagger服务路径
swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/{httpReq.Headers["X-Forwarded-Prefix"]}" } };
});
});
app.UseSwaggerUI(c =>
{
//使用相对路径
c.SwaggerEndpoint("v1/swagger.json", "My API V1");
});
集成nginx别忘了设置中间件
public static IServiceCollection AddNginx(this IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
return services;
}
github demo: https://github.com/wswind/swagger-proxy
官方文档: https://github.com/domaindrivendev/Swashbuckle.AspNetCore#modify-swagger-with-request-context
相关issue:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1617
https://github.com/microsoft/service-fabric-issues/issues/327
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/662
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/427
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/380
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1298#issuecomment-620269062
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1253
---- update 20220304 ----
除了上述方法外,也可以设置PathBase,设置PathBase对于MVC资源也生效,是处理这种转发带中间路径情况的通用方案。
微软的eShop Demo采用的是这种方式,不过是用过配置文件来设置的PathBase,代码如下
//https://github.com/dotnet-architecture/eShopOnContainers/blob/dev/src/Services/Ordering/Ordering.API/Startup.cs
var pathBase = Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase))
{
loggerFactory.CreateLogger<Startup>().LogDebug("Using PATH BASE '{pathBase}'", pathBase);
app.UsePathBase(pathBase);
}
app.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Ordering.API V1");
c.OAuthClientId("orderingswaggerui");
c.OAuthAppName("Ordering Swagger UI");
});
你使用PathBase的方式和X-Forwarded-Prefix结合一下,在设置nginx转发中间件的同时,基于X-Forwarded-Prefix设置一下PathBase,如
public static IApplicationBuilder UseForwardedPrefix(this IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
//https://github.com/dotnet/aspnetcore/issues/23263#issuecomment-767394044
if (ctx.Request.Headers.TryGetValue("X-Forwarded-Prefix", out var prefixVals))
{
if (!StringValues.IsNullOrEmpty(prefixVals))
{
string prefix = prefixVals.Last();
ctx.Request.PathBase = $"/{prefix}";
}
}
await next();
});
return app;
}
最后再基于PathBase来设置Swagger UI路径。
本文采用 知识共享署名 4.0 国际许可协议 进行许可