.Net Core Swagger 文档在添加 SwaggerDoc 时产生 404

.Net Core Swagger documentation yields 404 when adding SwaggerDoc

今晚我 运行 在我的 .NET 6 应用程序中尝试配置 Swagger 时遇到了最奇怪的问题。有趣的代码如下所示:

public static void Main(string[] args)
{
    // --- Code that used to go in Startup.ConfigureService --- 
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
    
    builder.Services.AddSwaggerGen(
        options =>
        {
            //options.SwaggerDoc("Foobar", new OpenApiInfo(){Title = "Some title"});
        });
    
    
    var app = builder.Build();

    // --- Code that used to go in Startup.Configure --- 
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    app.UseSwagger();
    app.UseSwaggerUI(x => x.SwaggerEndpoint("/swagger/v1/swagger.json", "Some title"));


    // --- Run the application --- 
    app.Run();
}

当我调试应用程序时,Swagger 页面显示正确,我可以看到控制器方法等。但是,如果我在第 5 行添加 options.SwaggerDoc(...)(现已注释掉),Swagger 页面显示弹出文本“响应状态为 404 /swagger/v1/swagger.json”。 知道为什么吗?

获取生成文档​​的默认 url 是 http[s]://localhost:<port>/swagger/v1/swagger.json,UI 是 https://localhost:<port>/swagger。但是当你添加这一行时:

options.SwaggerDoc("Foobar", new OpenApiInfo(){Title = "Some title"});

而url的模式是:

http[s]://localhost:<port>/swagger/{swaggerDocName}/swagger.json

因此您需要更改此行:

 app.UseSwaggerUI(x => x.SwaggerEndpoint("/swagger/Foobar/swagger.json", "Some title"));