以编程方式设置Swagger,而不是配置文件

vsnjm48y  于 2022-12-29  发布在  其他
关注(0)|答案(1)|浏览(160)

我正在使用最小的API,我正在为我的.net6应用程序使用OpenAPI支持(Swagger)。
自动生成的launchSettings.json文件的中间部分如下所示:

"profiles": {
"WebApplication1": {
  "commandName": "Project",
  "dotnetRunMessages": true,
  "launchBrowser": true,
  "launchUrl": "swagger",
  "applicationUrl": "https://localhost:7087;http://localhost:5285",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  }
}

我的问题是如何在C#代码中设置Swagger设置,以匹配该json文档中的Swagger设置?
这是自动生成的Program类:

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddAuthorization();

        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();

        app.UseAuthorization();

        var summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        app.MapGet("/weatherforecast", (HttpContext httpContext) =>
        {
            var forecast = Enumerable.Range(1, 5).Select(index =>
                new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = summaries[Random.Shared.Next(summaries.Length)]
                })
                .ToArray();
            return forecast;
        })
        .WithName("GetWeatherForecast");

        app.Run();
    }
}

如何才能做到这一点?

zwghvu4y

zwghvu4y1#

请看这篇文章来开始,长话短说就是查找现有的调用来指定需要什么。
A clean way to add Swagger to ASP.NET Core application

相关问题