c# - 使用 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; }
}
}
如何实现?
解决方案
您可以使用 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);
推荐阅读
- javascript - 在 javascript 中使用 for of 循环迭代对象数组
- ruby - 如何用正则表达式匹配开头和结尾的字符串
- r - 在不更改类的情况下为矩阵分配名称
- c# - 从逗号分隔的字符串在 C# 中设置对象
- c# - API 未从 HttpClient 获取参数
- spring - Spring Boot: Full authentication is required to access this resource in OAUTH2
- video - FFMPEG为视频添加圆形遮罩,转换为黑白并连接
- r - 使用不同的列(自变量)执行多重滚动回归
- php - 使用 domxpath 解析一些复杂的嵌套 html
- javascript - 在 iframe 按钮单击时创建缩放功能(相同域)