如何在ASP.NET Core中为openapi.json添加示例值



在OpenAPI 3.0中,有一个添加示例功能。我可以为Swagger UI添加一些示例值。我使用的是ASP.NET Core 6 Web API。是否可以将这些示例值添加到API操作中,并将这些示例数值反映到由ASP.NET Core自动生成的openapi.json中?

通过使用<example>

public class MyRequest
{
/// <summary>
/// Email parameter.
/// </summary>
/// <example>cool-service-account@my-cool-org.com</example>
[Required]
public string Email { get; set; }
}

并将其添加到Startup.cs

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My Good API",
Version = "v1",
Description = "Doesn't hurt to add some description."
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});

Bumbling up@CodingMytra的建议,有关更多选项,请参阅此处和此处

最新更新