我有一个小程序,该程序接受程序集并产生所有相关的OpenApiDocument
。现在,我的问题是,可以将其导入Swagger吗?我知道您可以在创建文档后添加用于修改文档的过滤器,但是我想知道是否可以为Swagger提供文档并规避自动生成。
在IDocumentFilter
内部,它允许您修改Swagger创建的OpenApiDocument
,但是我想使用自己的OpenApiDocument
。
public interface IDocumentFilter
{
void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context);
}
这里是我要配置Swagger以使用预定义的OpenApiDocument
:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(setupAction => TODO);
}
public void Configure(IApplicationBuilder app, IApiVersionDescriptionProvider provider)
{
}
这里是配置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();
}
我相信通过反复试验,我找到了可行的解决方案。
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}");
}
});
}