SwaggerApi.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. 
  2. using Microsoft.AspNetCore.Mvc.ApiExplorer;
  3. using System.ComponentModel;
  4. namespace OASystem.API
  5. {
  6. public class SwaggerApi : IDocumentFilter
  7. {
  8. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
  9. public class HideApiAttribute : System.Attribute { }
  10. public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
  11. {
  12. foreach (ApiDescription description in context.ApiDescriptions)
  13. {
  14. if (description.TryGetMethodInfo(out MethodInfo method))
  15. {
  16. if (method.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(HideApiAttribute))
  17. || method.CustomAttributes.Any(t => t.AttributeType == typeof(HideApiAttribute))
  18. )
  19. {
  20. string key = "/" + description.RelativePath;
  21. if (key.Contains("?"))
  22. {
  23. int idx = key.IndexOf("?", System.StringComparison.Ordinal);
  24. key = key.Substring(0, idx);
  25. }
  26. swaggerDoc.Paths.Remove(key);
  27. }
  28. }
  29. }
  30. }
  31. }
  32. }