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

Exposing a Schema that is not exposed by default with Swagger

Swagger 默认公开公开控制器(API 端点)使用的任何模式。如果控制器 未使用 模式 (class),如何公开它?

例如,Swagger 显示以下模式:

但是,需要公开 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; }
    }
}

如何实现?

您可以使用 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);
    }
}

class 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.