解決 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

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

解決方法:

  1. 使用url相對路徑
  2. 通過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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM