Home > front end >  Editing media type in Swagger with Swashbuckle
Editing media type in Swagger with Swashbuckle

Time:03-09

I am trying to create a simple POC app in ASP .NET Core. The goal is to edit the example value and media type of an endpoint to a custom value, for example CSV. I am just using the basic Weather Forecast template app to try this out, the code looks like this:

    [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();
        }
    }

The things I changed from the are:

  • installed Swashbuckle.AspNetCore.Filters
  • added [Produces("text/csv")] attribute tag to the GET endpoint, which changed the media type in Swagger to text/csv (this is working well)
  • added [SwaggerResponseExample(200, typeof(ForecastExample))] attribute to the GET endpoint - this should change the example in Swagger, but it's not working

I am registering the ExamplesOperationFilter in Program.cs like this:

builder.Services.AddSwaggerExamples();

The ForecastExample class which should define the response looks like this:

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

With this code, I would expect to see the Example Value in Swagger to just say "test", but it looks like this:

enter image description here

I've been following the steps described here enter image description here

  • Related