Swashbuckle을 사용하여 WebAPI의 Swagger 문서에서 메서드를 생략하는 방법
Swashbuckle을 사용하여 API 문서가 자동으로 생성되는 C # ASP.NET WebAPI 응용 프로그램이있습니다. 에서 설명서 특정 메서드 를 생략 하고 싶지만 자신감 UI 출력에 포함하지 않도록 자신감에 지시하는 방법을 알아낼 수없는.
나는 그것이 모델이나 스키마 필터 를 추가하는 것과 관련이 있다고 생각하지만 무엇을 해야할지 명확하지 않은 것이 문서는 출력에서 완전히 제거하지 않고 메소드의 출력을 수정하는 방법에 대한 예제 만하는 제공하는 것입니다.
미리 감사드립니다.
생성 된 문서에서 제외하기 위해 컨트롤러 및 작업에 다음 속성을 추가 할 수 있습니다. [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;
}
}
}
그리고 당신의 허풍 구성에서 :
...EnableSwagger(conf =>
{
// ...
conf.DocumentFilter<RemoveVerbsFilter>();
});
누군가 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 Config 클래스에서 해당 문서 필터를 추가하십시오.
public class SwaggerConfig
{
public static void Register(HttpConfiguration config)
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
config
.EnableSwagger(c =>
{
...
c.DocumentFilter<HideInDocsFilter>();
...
})
.EnableSwaggerUi(c =>
{
...
});
}
}
마지막 단계는 Swashbuckle이 문서를 생성하지 않기 위해 또는 방법에 [HideInDocsAttribute] 속성을 추가하는 것입니다.
경로 항목에 대한 사전 항목을 완전히 제거하고 싶습니다.
var pathsToRemove = swaggerDoc.Paths
.Where(pathItem => !pathItem.Key.Contains("api/"))
.ToList();
foreach (var item in pathsToRemove)
{
swaggerDoc.Paths.Remove(item.Key);
}
이 접근 방식을 사용하면 생성 된 swagger.json 정의에 "빈"항목이 표시되지 않습니다.
@spottedmahns 답변을 기반으로 합니다. 내 임무는 그 반대였습니다. 허용 된 항목 만 표시하십시오.
프레임 워크 : .NetCore 2.1; 스웨거 : 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>();
});
}
필터 만들기
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]
});
Swagger JSON에 포함하려는 메소드 및 컨트롤러에 [SwaggerTag] 속성을 추가하십시오.
'IT' 카테고리의 다른 글
| Bash에서 각 파일과 디렉토리의 크기를 (재귀 적으로) 어느 정도 정렬해야합니까? (0) | 2020.08.14 |
|---|---|
| Ref, Var, Agent, Atom의 Clojure 차이점 (예제 포함) (0) | 2020.08.14 |
| Docker 실행을 통해 셸 펼쳐보기에 인수를 전달하는 방법 (0) | 2020.08.14 |
| RegEx가없는 String.replaceAll (0) | 2020.08.14 |
| EC2에서 파일을 다운로드해야합니까? (0) | 2020.08.14 |