使用 Swagger 公开默认未公开的架构

时间:2021-05-27 15:42:43

标签: c# swagger swagger-ui swashbuckle

Swagger 默认公开暴露的控制器(API 端点)使用的任何架构。如果控制器使用架构(类),如何公开它?

例如,Swagger 显示以下架构:

Swagger Schemas

但是,Song Schema(如下)需要公开。它没有公开,因为它没有被控制器(API 端点)使用。

using System;
namespace ExampleNamespace
{
    public class Song
    {
        [Key][Required]
        public int SongID { get; set; }
        [Required]
        public string SongName { get; set; }
        public string SongDescription { get; set; }
        public int SongLength { get; set; } //seconds
        [Required]
        public int AlbumID { get; set; }
    }
}

如何实现?

1 个答案:

答案 0 :(得分:0)

您可以使用 DocumentFilter 添加架构

public class AddSongSchemaDocumentFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        var songSchema = new OpenApiSchema {...};
        songSchema.Properties.Add(new KeyValuePair<string, OpenApiSchema>("songName", new OpenApiSchema { ... }));
        ...

        context.SchemaRepository.Schemas.Add("Song", songSchema);
    }
}

OpenApiSchema 类用于歌曲架构本身和属性架构。此类型包含许多您可以设置的文档相关属性,例如 Description

你像这样注册AddSongSchemaDocumentFilter

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(options =>
    {
        options.DocumentFilter<AddSongSchemaDocumentFilter>();
    });
}

如果有很多属性,这可能有点乏味。使用反射,您可以迭代属性,甚至反射附加到这些属性的关联属性。

var songSchema = new OpenApiSchema() { };
var song = new Song();
var properties = typeof(Song).GetProperties();

foreach (var p in properties)
    songSchema.Properties.Add(new KeyValuePair<string, OpenApiSchema(
        p.Name,
        new OpenApiSchema()
        {
            Type = p.PropertyType.ToString(),
            Description = // get [Description] attribute from p,
            // ... etc. for other metadata such as an example if desired
        }));

context.SchemaRepository.Schemas.Add("Song", songSchema);

Full Swashbuckle documentation

相关问题