簡體   English   中英

如何在開發/測試和生產環境中配置 Swagger

[英]How to configure Swagger in Dev/Test and Production environment

我在我的 .NET 6 Web API 項目中配置了 Swagger。 在本地,我可以訪問 Swagger 文件。 下面是我的代碼。

 public static void ConfigureSwaggerMiddleware(this WebApplication app)
        {
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.yaml", "API V1");
                   
                });
            }
            else
            {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("swagger/v1/swagger.yaml", "API V1");
                    c.RoutePrefix = "api/abc";

                });
            }
        }

現在,我想在開發、測試和更高的環境中配置它的 URL,例如 https://devurl/api/abc/swagger.yaml。 我正在嘗試上面的代碼,但出現錯誤

沒有找到web地址的網頁:https://localhost:7120/swagger/index.html

如果只更改路由前綴,恐怕無法實現您想要的。

public static IApplicationBuilder UseSwaggerUI(
            this IApplicationBuilder app,
            Action<SwaggerUIOptions> setupAction = null)
        {
            SwaggerUIOptions options;
            using (var scope = app.ApplicationServices.CreateScope())
            {
                options = scope.ServiceProvider.GetRequiredService<IOptionsSnapshot<SwaggerUIOptions>>().Value;
                setupAction?.Invoke(options);
            }

            // To simplify the common case, use a default that will work with the SwaggerMiddleware defaults
            if (options.ConfigObject.Urls == null)
            {
                var hostingEnv = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
                options.ConfigObject.Urls = new[] { new UrlDescriptor { Name = $"{hostingEnv.ApplicationName} v1", Url = "v1/swagger.json" } };
            }

            return app.UseSwaggerUI(options);
        }

當我們沒有為使用 swagger UI 設置任何配置選項時,它會將默認的 URL 設置為v1/swagger.json和默認路由前綴public string RoutePrefix { get; set; } = "swagger"; public string RoutePrefix { get; set; } = "swagger"; 這使我們獲得swagger.json文件來加載索引頁面。 當您更改路由前綴值時,它會使您的 API 應用程序無法找到 swagger 配置文件,這將導致 404 錯誤。

所以我們需要更改launchsetting.json並添加app.UseSwagger選項。 我提到了這個答案

這是我在Program.cslaunchsetting.json中的配置,我更改了"launchUrl": "api/abc/swagger"

if (app.Environment.IsDevelopment())
{
    //app.UseSwagger();
    app.UseSwagger(c =>
    {
        c.RouteTemplate = "api/abc/swagger/{documentname}/swagger.json";
    });
    //app.UseSwaggerUI();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/api/abc/swagger/v1/swagger.json", "API V1");
        c.RoutePrefix = "api/abc/swagger";
    });
}

然后,每當 api 應用程序運行時,它將指向https://localhost:7212/api/abc/swagger/index.html並顯示 API。 這是我的測試結果。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM