docker 部署 netcore3.1项目,使用nginx反向代理,swagger 不能访问的问题 SwaggerUIBundle is not defined

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

部署在windows下 项目正常,直接用VS调试运行也正常显示,发布在Linux下无法访问,Linux下使用的是nginx代理,所以推测是nginx代理问题,

经过两天查阅和尝试,最终确认问题为

nginx是代理后url路径发生变化导致swagger无法定位到json。

下面为解决重要步骤:

在nginx中配置代理如下:

 server { listen 80; listen [::]:80; server_name localhost; # root /usr/share/nginx/html; location / { proxy_pass http://localhost:8084/;  proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-Prefix swagger; #------其中swagger可以更换任何路由 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; } # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; error_page 404 /404.html; location = /404.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }

netcore3.1 中注册swagger

app.UseSwagger(c=> { c.PreSerializeFilters.Add((doc, item) => { //根据代理服务器提供的协议、地址和路由,生成api文档服务地址 doc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{item.Scheme}://{item.Host.Value}/{item.Headers["X-Forwarded-Prefix"]}" } }; }); }); app.UseSwaggerUI(c => { c.ShowExtensions(); c.ValidatorUrl(null); c.SwaggerEndpoint("/swagger/v1/swagger.json", $"{ApiName} V1"); c.RoutePrefix = string.Empty; c.DocExpansion(DocExpansion.None); });

我的项目如下:

UseSwag 扩展方法如下:

 public static void UseSwag(this IApplicationBuilder app, params string[] versions) { app.UseSwagger(c => { c.PreSerializeFilters.Add((doc, item) => { //根据代理服务器提供的协议、地址和路由,生成api文档服务地址 doc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{item.Scheme}://{item.Host.Value}/{item.Headers["X-Forwarded-Prefix"]}" } }; }); }); // 配置SwaggerUI foreach (var version in versions) { app.UseSwaggerUI(c => { c.ShowExtensions(); c.ValidatorUrl(null); c.SwaggerEndpoint($"{Constants.VirtualPath}/swagger/{version}/swagger.json", version); c.RoutePrefix = string.Empty; c.DocExpansion(DocExpansion.None); }); } // }

Constants.VirtualPath 是个空字符串,这个是因为我司网址有前缀,需要加上不同的配置,例如 dev SIT

@天才卧龙的博客

原文地址:https://www.cnblogs.com/chenwolong/p/16179839.html

原文链接:http://www.manongjc.com/detail/29-ynwsryvnycrbduw.html

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享