为不同的API组生成多张幅JSON文件

时间:2020-06-22 09:00:13

标签: swagger swashbuckle

我在解决方案中配置了醒目的工具,它正确显示了API文档。现在,我最近在同一解决方案中开发了一些新的API,这些新API也出现在API文档中,并且这些项目也遵循相同的命名约定。 现在,我的要求是我希望将新的API文档与较旧的API文档分开,因此基本上我希望两个JSON文件相互生成,分别是旧API和新API。

我的Swagger配置如下所示。

  Config.EnableSwagger(@"api-docs/{apiVersion}",
            c =>
            {
                c.SingleApiVersion("v1", "SAMPLE API");
                c.UseFullTypeNameInSchemaIds();
                c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                foreach (String x in Directory.GetFiles(Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().CodeBase).Path)), "*.dll")
                    .Where(f => Path.GetFileNameWithoutExtension(f).ToLower().Contains("sample") ****&& !Path.GetFileNameWithoutExtension(f).ToLower().Contains("sample.api"))****
                     
                    .Select(f => String.Format(@"{0}\{1}.xml", Path.GetDirectoryName(f), Path.GetFileNameWithoutExtension(f)))
                    .Where(File.Exists))
                {
                    c.IncludeXmlComments(x);
                }
                c.OperationFilter<AddRequiredHeaderParameter>();
            });

我的新API项目命名为sample.api.test,旧API项目命名为sample.web.test。 我在where子句中添加了&&部分,以忽略在第一个JSON文档生成中选择新文件的过程,但是没有运气。我对此并不陌生,真的不知道是否有可能根据项目名称使用两个JSON。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我使用IDocumentFilter修复了此问题,

internal class SwaggerFilterOutControllers : IDocumentFilter
    {
        void IDocumentFilter.Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            
            var apiKeys = swaggerDoc.paths.Select(s => s.Key).ToList();
            foreach (var apiKey in apiKeys)
            {
                if (swaggerDoc.info.title == "old API" && apiKey.StartsWith("/latapi"))
                    swaggerDoc.paths.Remove(apiKey);
                else if (swaggerDoc.info.title == "New Public API" && !apiKey.StartsWith("/latapi"))
                    swaggerDoc.paths.Remove(apiKey);
            }
}
}

,然后在enableswagger()方法中,我将此过滤器称为

c.DocumentFilter<SwaggerFilterOutControllers>();