我有一个C# ASP.NET WebAPI应用程序,它使用Swashbuckle自动生成API文档。我希望能够从文档中省略某些方法,但我似乎不知道如何告诉Swagger不要将它们包含在Swagger输出中。
我感觉到这与添加模型或模式筛选器有关,但不清楚该做什么,文档似乎只提供了如何为方法修改输出的示例,而不是从输出中完全删除它。
发布于 2017-01-12 22:24:22
可以将以下属性添加到控制器和操作中,以将它们从生成的文档中排除在外:[ApiExplorerSettings(IgnoreApi = true)]
发布于 2020-06-08 21:07:44
可能对某人有帮助,但在开发(调试)期间,我们喜欢公开整个控制器和/或操作,然后在生产过程中隐藏这些操作(发布版本)。
#if DEBUG
[ApiExplorerSettings(IgnoreApi = false)]
#else
[ApiExplorerSettings(IgnoreApi = true)]
#endif 发布于 2017-02-14 20:08:40
有人在github上发布了解决方案,所以我要把它粘贴在这里。所有的功劳都归他。https://github.com/domaindrivendev/Swashbuckle/issues/153#issuecomment-213342771
首先创建一个属性类
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class HideInDocsAttribute : Attribute
{
}然后创建文档筛选器类。
public class HideInDocsFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
foreach (var apiDescription in apiExplorer.ApiDescriptions)
{
if (!apiDescription.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<HideInDocsAttribute>().Any() && !apiDescription.ActionDescriptor.GetCustomAttributes<HideInDocsAttribute>().Any()) continue;
var route = "/" + apiDescription.Route.RouteTemplate.TrimEnd('/');
swaggerDoc.paths.Remove(route);
}
}
}然后在Swagger类中,添加文档过滤器
public class SwaggerConfig
{
public static void Register(HttpConfiguration config)
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
config
.EnableSwagger(c =>
{
...
c.DocumentFilter<HideInDocsFilter>();
...
})
.EnableSwaggerUi(c =>
{
...
});
}
}最后一步是在Controller或方法上添加HideInDocsAttribute属性,您不希望Swashbuckle生成文档。
https://stackoverflow.com/questions/29701573
复制相似问题