【发布时间】:2022-09-24 04:58:32
【问题描述】:
我正在尝试在 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();
}
}
我改变的事情是:
- 已安装 Swashbuckle.AspNetCore.Filters
- 将 [Produces(\"text/csv\")] 属性标签添加到 GET 端点,这将 Swagger 中的媒体类型更改为 text/csv(效果很好)
- 将 [SwaggerResponseExample(200, typeof(ForecastExample))] 属性添加到 GET 端点 - 这应该会更改 Swagger 中的示例,但它不起作用
我在 Program.cs 中注册了 ExamplesOperationFilter,如下所示:
builder.Services.AddSwaggerExamples();
应该定义响应的 ForecastExample 类如下所示:
public class ForecastExample : IExamplesProvider<string>
{
public string GetExamples()
{
return \"test\";
}
}
使用此代码,我希望看到 Swagger 中的示例值只是说“测试”,但它看起来像这样:
我一直按照这里描述的步骤https://freesoft.dev/program/89951254 但我想我错过了一些重要的东西。提前感谢您的帮助!
标签: c# asp.net-core swagger swashbuckle swashbuckle.aspnetcore