如何让 swagger 在 .net core web 中使用自定义 swagger 文件而不是自动生成的文件 api

How to make swagger use custom swagger file instead of auto-generated file in .net core web api

创建了新的 .net core 3.1 Web Api 项目并将 Swashbuckle 配置为使用 swagger。

一切正常,但我需要我的应用程序使用我自己的 swagger 规范文件而不是自动生成的文件(\swagger\v1\swagger.json)

我搜索了很多帖子,例如 ,但其中 none 对这里有帮助。

我已经在项目的根路径(与 .csproj 相同的目录)中创建了 my-custom-swagger.json 文件

Startup.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseStaticFiles();
        app.UseSwagger();

    //    app.UseStaticFiles(new StaticFileOptions
    //{
    //    FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory),
    //    RequestPath = "my-custom-swagger.json"
    //    });

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core Test SW");
            c.RoutePrefix = string.Empty;
        });

如何使 swagger 使用 my-custom-swagger.json 文件而不是自动生成的文件

如果您想为 swaggerUI 提供自己的自定义 swagger/OpenAPI 文件,那么您需要执行以下操作(c# .net5 中的代码)

在 ConfigureServices() 中添加

   .AddSwaggerGen()

.AddSwaggerGenNewtonsoftSupport()如果你依赖Newtonsoft.Json序列化

在配置中添加

    .UseSwagger()
    .UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/internal/swagger.json", "v1");
    })

现在我们需要使用我们的自定义文件公开端点。

    .UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/internal/swagger.json", async context =>
        {
            await context.Response.WriteAsync(await File.ReadAllTextAsync("my-custom-swagger.json"));
        });
            
        // the rest of your code goes here
    });

我只是 运行 喜欢这个。我不明白为什么这应该很简单。

无论如何,我用 Startup.cs (.Net Core 5) 中的这段代码解决了它:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();
        services.AddSwaggerGen();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "Swagger")),
                RequestPath = "/CustomSwagger"
            });

            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/CustomSwagger/customswagger.json", "MySwagger"));
        }
    //...

rootSolutionFolder/Swagger 中有 customswagger.json,正如在 PhysicalFileProvider 部分中看到的那样,并将其映射到 /CustomSwagger,因此我可以在 app.UseSwaggerUI 中使用它]部分。