[英]Import OpenAPI Document or JSON during Swagger Generation
I have a small program that takes in an assembly and produces all relevant OpenApiDocument
.我有一个小程序,它接收一个程序集并生成所有相关的OpenApiDocument
。 Now, my question is, can this be imported into Swagger?现在,我的问题是,这可以导入到 Swagger 中吗? I know you can add filters for modifying the documents after they have been created, but I am wondering if you can give Swagger the documents and circumvent the auto-generation.我知道您可以添加过滤器以在创建文档后修改文档,但我想知道您是否可以将文档提供给 Swagger 并绕过自动生成。
Inside of the IDocumentFilter
it allows you to modify the OpenApiDocument
that Swagger creates, but I would like to use my own OpenApiDocument
.在IDocumentFilter
内部,它允许您修改 Swagger 创建的OpenApiDocument
,但我想使用我自己的OpenApiDocument
。
public interface IDocumentFilter
{
void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context);
}
Here is where I want to configure Swagger to use the predefined OpenApiDocument
:这是我想配置 Swagger 以使用预定义的OpenApiDocument
:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(setupAction => TODO);
}
public void Configure(IApplicationBuilder app, IApiVersionDescriptionProvider provider)
{
}
Here are the publicly available methods that I want to utilize in the API startup when configuring Swagger:以下是我在配置 Swagger 时想在 API 启动中使用的公开可用方法:
public static IEnumerable<OpenApiDocument> CreateDocuments(this Assembly assembly, string title, string description, string name, string email)
{
return ControllerInfo.FindControllers(assembly)
.GroupBy(controller => controller.Version)
.OrderBy(group => group.Key)
.Select(group => CreateDocument(group.Key, group, title, description, name, email));
}
public static string ToJson(this OpenApiDocument document)
{
using var outputString = new StringWriter();
document.SerializeAsV3(new OpenApiJsonWriter(outputString));
return outputString.ToString();
}
I believe through some trial and error I came to a working solution.我相信通过一些反复试验,我找到了一个可行的解决方案。
public void ConfigureSwagger(IApplicationBuilder app)
{
const string swagger = "Swagger";
var directory = Path.Combine(Directory.GetCurrentDirectory(), swagger);
Directory.CreateDirectory(directory);
app.UseDefaultFiles().UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(directory),
RequestPath = $"/{swagger}"
});
app.UseSwaggerUI(c =>
{
foreach (var document in Assembly.GetExecutingAssembly().CreateDocuments("title", "description", "name", "email"))
{
var file = $"swagger{document.Info.Version}.json";
File.WriteAllText(Path.Combine(directory, file), document.ToJson());
c.SwaggerEndpoint($"/{swagger}/{file}", $"{document.Info.Title} {document.Info.Version}");
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.