首页 > 解决方案 > 使用 Swagger 公开默认未公开的 Schema

问题描述

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

例如,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; }
    }
}

如何实现?

标签: c#swaggerswagger-uiswashbuckle

解决方案


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

完整的 Swashbuckle 文档


推荐阅读