Ответ 1
Вы можете добавить следующие атрибуты к контроллерам и действиям, чтобы исключить их из сгенерированной документации: [ApiExplorerSettings(IgnoreApi = true)]
У меня есть приложение ASP.NET ASP.NET ASP.NET с документацией API, которое автоматически создается с помощью Swashbuckle. Я хочу, чтобы опустить определенные методы из документации, но я не могу понять, как сказать Swagger не включать их в выход интерфейса Swagger.
Я чувствую, что это связано с добавлением модели или схемы, но не очевидно, что делать, и в документации, как представляется, приводятся примеры того, как модифицировать вывод для метода, не удаляйте его полностью с выхода.
Спасибо заранее.
Вы можете добавить следующие атрибуты к контроллерам и действиям, чтобы исключить их из сгенерированной документации: [ApiExplorerSettings(IgnoreApi = true)]
Вы можете удалить "операции" из документа swagger после того, как он сгенерирован с помощью фильтра документа - просто установите глагол в null
(хотя могут быть и другие способы сделать это)
Следующий пример позволяет использовать только GET
глаголы - и берется из этой проблемы.
class RemoveVerbsFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
foreach (PathItem path in swaggerDoc.paths.Values)
{
path.delete = null;
//path.get = null; // leaving GET in
path.head = null;
path.options = null;
path.patch = null;
path.post = null;
path.put = null;
}
}
}
и в вашей конфигурации swagger:
...EnableSwagger(conf =>
{
// ...
conf.DocumentFilter<RemoveVerbsFilter>();
});
Кто-то разместил решение на github, поэтому я собираюсь вставить его здесь. Все кредиты идут к нему. https://github.com/domaindrivendev/Swashbuckle/issues/153#issuecomment-213342771
Сначала создайте класс Attribute
[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 Config добавьте этот фильтр документов.
public class SwaggerConfig
{
public static void Register(HttpConfiguration config)
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
config
.EnableSwagger(c =>
{
...
c.DocumentFilter<HideInDocsFilter>();
...
})
.EnableSwaggerUi(c =>
{
...
});
}
}
Последний шаг - добавить атрибут [HideInDocsAttribute] в Controller или Method, чтобы Swashbuckle не генерировал документацию.
Я бы предпочел полностью удалить словарные записи для элементов пути:
var pathsToRemove = swaggerDoc.Paths
.Where(pathItem => !pathItem.Key.Contains("api/"))
.ToList();
foreach (var item in pathsToRemove)
{
swaggerDoc.Paths.Remove(item.Key);
}
При таком подходе вы не получите "пустые" элементы в сгенерированном определении swagger.json.
Сделать фильтр
public class SwaggerTagFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
foreach(var contextApiDescription in context.ApiDescriptions)
{
var actionDescriptor = (ControllerActionDescriptor)contextApiDescription.ActionDescriptor;
if(!actionDescriptor.ControllerTypeInfo.GetCustomAttributes<SwaggerTagAttribute>().Any() &&
!actionDescriptor.MethodInfo.GetCustomAttributes<SwaggerTagAttribute>().Any())
{
var key = "/" + contextApiDescription.RelativePath.TrimEnd('/');
swaggerDoc.Paths.Remove(key);
}
}
}
}
Сделать атрибут
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class SwaggerTagAttribute : Attribute
{
}
Подать заявку в startup.cs
services.AddSwaggerGen(c => {
c.SwaggerDoc(1,
new Info { Title = "API_NAME", Version = "API_VERSION" });
c.DocumentFilter<SwaggerTagFilter>(); // [SwaggerTag]
});
Добавьте атрибут [SwaggerTag] в методы и контроллеры, которые вы хотите включить в Swagger JSON.
Основано на ответе @spottedmahns. Моя задача была наоборот. Показывать только те, которые разрешены.
Фреймворки:.NetCore 2.1; Swagger: 3.0.0
Добавлен атрибут
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class ShowInSwaggerAttribute : Attribute
{
}
И реализовать пользовательский IDocumentFilter
public class ShowInSwaggerFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
foreach (var contextApiDescription in context.ApiDescriptions)
{
var actionDescriptor = (ControllerActionDescriptor) contextApiDescription.ActionDescriptor;
if (actionDescriptor.ControllerTypeInfo.GetCustomAttributes<ShowInSwaggerAttribute>().Any() ||
actionDescriptor.MethodInfo.GetCustomAttributes<ShowInSwaggerAttribute>().Any())
{
continue;
}
else
{
var key = "/" + contextApiDescription.RelativePath.TrimEnd('/');
var pathItem = swaggerDoc.Paths[key];
if(pathItem == null)
continue;
switch (contextApiDescription.HttpMethod.ToUpper())
{
case "GET":
pathItem.Get = null;
break;
case "POST":
pathItem.Post = null;
break;
case "PUT":
pathItem.Put = null;
break;
case "DELETE":
pathItem.Delete = null;
break;
}
if (pathItem.Get == null // ignore other methods
&& pathItem.Post == null
&& pathItem.Put == null
&& pathItem.Delete == null)
swaggerDoc.Paths.Remove(key);
}
}
}
}
Код ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
// other code
services.AddSwaggerGen(c =>
{
// other configurations
c.DocumentFilter<ShowInSwaggerFilter>();
});
}
Я хочу добавить еще атрибут в документ Swagger с интерфейсом IDOCUMENTFILTER. Я хочу добавить ошибку: код описания в документе Swagger.
Как мы можем это сделать?