解决 asp.net core swagger nginx 代理服务器转发后,无法访问的问题 Swashbuckle

2021-02-15 14:24

阅读:568

标签:select   agg   view   代理服务器   inux   地址   cti   was   ase   

原文:解决 asp.net core swagger nginx 代理服务器转发后,无法访问的问题 Swashbuckle

通过代理转发后,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

Copy
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

解决方法:

  1. 使用url相对路径
  2. 通过PreSerializeFilters设置根地址,并通过nginx的X-Forwarded-Prefix指定api名称

nginx配置:

Copy
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属性

代码如下:

Copy
app.UseSwagger(c => { c.PreSerializeFilters.Add((swagger, httpReq) => { //根据访问地址,设置swagger服务路径 swagger.Servers = new List { 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

解决 asp.net core swagger nginx 代理服务器转发后,无法访问的问题 Swashbuckle

标签:select   agg   view   代理服务器   inux   地址   cti   was   ase   

原文地址:https://www.cnblogs.com/lonelyxmas/p/12983766.html


评论


亲,登录后才可以留言!