使用 Swagger 公开默认未公开的架构 [英] Exposing a Schema that is not exposed by default with Swagger

查看:52
本文介绍了使用 Swagger 公开默认未公开的架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Swagger exposes by default any schema that is used by an exposed controller (API end point). How can a schema (class) be exposed if it is not used by a controller?

例如,Swagger 显示以下架构:

For example, Swagger is showing the following Schemas:

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

But, the Song Schema (below) needs to be exposed. It is not exposed because it is not used by a controller (API end point).

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 添加架构

You can add a schema using a 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.

The class OpenApiSchema is used for the song schema itself, and for property schemas. This type contains a number of documentation related properties you can set such as Description.

你像这样注册AddSongSchemaDocumentFilter

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

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

This could be a bit tedious if there are many properties. Using reflection, you can iterate on the properties, and even reflect on associated attributes attached to those properties.

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 文档.

这篇关于使用 Swagger 公开默认未公开的架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆