1. 程式人生 > 其它 >.net 5.0 隱藏swagger介面特性標識

.net 5.0 隱藏swagger介面特性標識

新建一個擴充套件類HiddenApiFilter,繼承IDocumentFilter
/// <summary>
/// 隱藏接⼝,不⽣成到swagger⽂檔展⽰
/// </summary>
public class HiddenApiFilter : IDocumentFilter
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public partial class HiddenApiAttribute : System.Attribute { }

/// <summary>
/// 隱藏swagger特性標識
/// </summary>
/// <param name="swaggerDoc"></param>
/// <param name="context"></param>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
foreach (ApiDescription apiDescription in context.ApiDescriptions)
{
if (apiDescription.TryGetMethodInfo(out MethodInfo method))
{
if (method.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute)) ||
method.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute)))
{
string key = "/" + apiDescription.RelativePath;
if (key.Contains("?"))
{
int idx = key.IndexOf("?", System.StringComparison.Ordinal);
key = key.Substring(0, idx);
}
swaggerDoc.Paths.Remove(key);
}
}
}
}
}

新增startup註冊程式碼

public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();

services.AddRazorPages();

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" });

c.CustomSchemaIds(type => type.FullName); // 解決相同類名會報錯的問題
//API介面檔案路徑
var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "WebApplication1.xml");
c.IncludeXmlComments(filePath);

//新增對控制器的標籤(描述)
c.DocumentFilter<ApplyTagDescriptions>();
//隱藏api
c.DocumentFilter<HiddenApiFilter>();
});

services.AddMvc();
}