使用 Swashbuckle 在 Swagger 中编辑媒体类型

Editing media type in Swagger with Swashbuckle

我正在尝试在 ASP .NET Core 中创建一个简单的 POC 应用程序。目标是将端点的示例值和媒体类型编辑为自定义值,例如 CSV。我只是使用基本的天气预报模板应用程序来尝试一下,代码如下所示:

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
        
        [HttpGet("weather")]
        [Produces("text/csv")]
        [SwaggerResponseExample(200, typeof(ForecastExample))]
        public IEnumerable<WeatherForecast> Get()
        {
            return 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();
        }
    }

我改变的是:

我正在 Program.cs 中注册 ExamplesOperationFilter,如下所示:

builder.Services.AddSwaggerExamples();

应定义响应的 ForecastExample class 如下所示:

    public class ForecastExample : IExamplesProvider<string>
    {
        public string GetExamples()
        {
            return "test";
        }
    }

使用这段代码,我希望看到 Swagger 中的示例值只是说“测试”,但它看起来像这样:

我一直在按照此处描述的步骤操作 https://freesoft.dev/program/89951254 但我想我错过了一些关键的东西。在此先感谢您的帮助!

您需要像这样配置您的 'program.cs'

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
//.......
builder.Services.AddSwaggerGen(c =>
{
    c.ExampleFilters();
});

builder.Services.AddSwaggerExamplesFromAssemblyOf<ForecastExample>();
//.......