通過代理轉發后,webapi的swagger無法訪問,本質原因是代理后url路徑發生變化導致swagger無法定位到json。
官方文檔配置:
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");
});
github demo: https://github.com/wswind/swagger-proxy
相關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