渲染CSV示例swashbuckle

发布于 2025-01-24 16:47:55 字数 1149 浏览 2 评论 0原文

我有一个可以返回CSV或JSON的API,对接受标题MimeType。

我已经用[careed(“ application/json”,“ text/csv”)进行了装饰该方法]。这是一个带有ASP.NET核心默认项目的MRE:

public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    public string? Summary { get; set; }
}
[HttpGet(Name = "GetWeatherForecast")]
[Produces("application/json","text/csv")]
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 = "Freezing"
    })
    .ToArray();
}

这可以在Swagger UI中进行MimeType选择,并且可以正确地添加到请求的Accept标题中。我的问题是,示例响应值不是以CSV的格式,而是作为JSON。

我如何配置如何为自定义模拟型(例如文本/CSV)渲染示例?

我正在使用swashbuckle.aspnetcore版本6.3.1。

I have an API that can return an csv or json, deppending on the Accept header mimetype.

I've decorated the method with [Produces("application/json","text/csv")]. Here it is a MRE with the ASP.NET Core default project:

public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    public string? Summary { get; set; }
}
[HttpGet(Name = "GetWeatherForecast")]
[Produces("application/json","text/csv")]
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 = "Freezing"
    })
    .ToArray();
}

This enables the mimetype selection in the Swagger UI, and it's being correct added to the Accept header of the request. My issue is that the example response value is not being formatted as csv, but as json.

Example value for the csv mimetype

How can I configure how examples are rendered for custom mimetypes, like text/csv?

I'm using Swashbuckle.AspNetCore Version 6.3.1.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沙与沫 2025-01-31 16:47:55

您应该使用swashbuckle.aspnetcore.examples软件包。

您可以参考下面的帖子。

swagger in Swagger in Swagger 编辑媒体类型

You should use Swashbuckle.AspNetCore.Examples package.

And you can refer below post.

Editing media type in Swagger with Swashbuckle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文