我有一个 ASP.NET Core 7 Web api,带有各种输出格式化程序,如 CSV、XML、纯文本等。
我在
AddControllers
方法中添加这些格式化程序,例如:
builder.Services.AddControllers(options =>
{
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
options.OutputFormatters.Add(new CsvOutputFormatter());
options.OutputFormatters.Add(new MyCustomOutputFormatter());
});
仅此而已,Swashbuckle 就会识别出我的 API 具有不同的响应媒体类型,并将它们添加到 Swagger UI 中的“媒体类型”选择中。
问题是它无法为每种媒体类型生成示例响应
我可以自己生成这些示例吗?
在类定义中,您可以在正文中添加注释。使用
<example></example>
标签来包装值
首先将
IncludeXmlComments
方法添加到生成的文档中。
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo
{
Title = "My API - V1",
Version = "v1"
}
);
var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
c.IncludeXmlComments(filePath);
}
然后你可以用 xml 标签注释你的
class
。
public class Product
{
/// <summary>
/// The name of the product
/// </summary>
/// <example>Men's basketball shoes</example>
public string Name { get; set; }
/// <summary>
/// Quantity left in stock
/// </summary>
/// <example>10</example>
public int AvailableStock { get; set; }
/// <summary>
/// The sizes the product is available in
/// </summary>
/// <example>["Small", "Medium", "Large"]</example>
public List<string> Sizes { get; set; }
}
注意:您还可以通过使用摘要标签注释 API 模型及其属性来提供 Swagger 架构描述。如果您有多个 XML 注释文件(例如控制器和模型的单独库),您可以多次调用 IncludeXmlComments 方法,它们将全部合并到输出的 Swagger JSON 中。