歡迎光臨
每天分享高質量文章

Asp.Net Core WebAPI使用Swagger時API隱藏與分組

1、前言

為什麼我們要隱藏部分介面?

因為我們在用swagger代替介面的時候,難免有些介面會直觀的暴露出來,比如我們結合Consul一起使用的時候,會將健康檢查介面以及報警通知介面暴露出來,這些介面有時候會出於方便考慮,沒有進行加密,這個時候我們就需要把介面隱藏起來,只有內部的開發者知道。

為什麼要分組?

通常當我們寫前後端分離的專案的時候,難免會遇到編寫很多介面供前端頁面進行呼叫,當介面達到幾百個的時候就需要區分哪些是框架介面,哪些是業務介面,這時候給swaggerUI的介面分組是個不錯的選擇。

swagger的基本使用這裡將不再贅述,可以閱讀微軟官方檔案,即可基本使用

2、swaggerUI中加入授權請求

  • 新建 HttpHeaderOperationFilter 操作過濾器,繼承 Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter 介面,實現 Apply 方法

    ///
    /// swagger請求頭
    ///

    
    

public class HttpHeaderOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
#region 新方法
if (operation.Parameters == null)
{
operation.Parameters = new List();
}

if (context.ApiDescription.TryGetMethodInfo(out MethodInfo methodInfo))
{
if (!methodInfo.CustomAttributes.Any(t => t.AttributeType == typeof(AllowAnonymousAttribute))
&&!(methodInfo.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(AuthorizeAttribute))))
{
operation.Parameters.Add(new NonBodyParameter
{
Name = “Authorization”,
In = “essay-header”,
Type = “string”,
Required = true,
Description = “請輸入Token,格式為bearer XXX”
});
}
}
#endregion

#region 已過時
//if (operation.Parameters == null)
//{
// operation.Parameters = new List();
//}
//var actionAttrs = context.ApiDescription.ActionAttributes().ToList();
//var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
//if (isAuthorized == false)
//{
// var controllerAttrs = context.ApiDescription.ControllerAttributes();
// isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
//}
//var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
//if (isAuthorized && isAllowAnonymous == false)
//{
// operation.Parameters.Add(new NonBodyParameter
// {
// Name = “Authorization”,
// In = “essay-header”,
// Type = “string”,
// Required = true,
// Description = “請輸入Token,格式為bearer XXX”
// });
//}
#endregion
}
}

  • 然後修改 Startup.cs 中的 ConfigureServices 方法,新增我們自定義的 HttpHeaderOperationFilter 過濾器
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSwaggerGen(c =>
        {
            ...
            c.OperationFilter();
        });
        ...
    }

    這時候我們再訪問swaggerUI就可以輸入Token了

3、API分組

  • 修改 Startup.cs 中的 ConfigureServices 方法,新增多個swagger檔案
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "介面檔案",
                Description =  "介面檔案-基礎",
                TermsOfService = "",
                Contact = new Contact
                {
                    Name = "XXX1111",
                    Email = "XXX1111@qq.com",
                    Url = ""
                }
            });
    
            c.SwaggerDoc("v2", new Info
            {
                Version = "v2",
                Title = "介面檔案",
                Description =  "介面檔案-基礎",
                TermsOfService = "",
                Contact = new Contact
                {
                    Name = "XXX2222",
                    Email = "XXX2222@qq.com",
                    Url = ""
                }
            });
    
            //反射註入全部程式集說明
            GetAllAssemblies().Where(t => t.CodeBase.EndsWith("Controller.dll")).ToList().ForEach(assembly =>
                {
                    c.IncludeXmlComments(assembly.CodeBase.Replace(".dll", ".xml"));
                });
    
            c.OperationFilter();
            //c.DocumentFilter();
        });
        ...
    }
  • 修改 Startup.cs 中的 Configure 方法,加入
    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        ...
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v2/swagger.json", "介面檔案-基礎");//業務介面檔案首先顯示
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "介面檔案-業務");//基礎介面檔案放後面後顯示
            c.RoutePrefix = string.Empty;//設定後直接輸入IP就可以進入介面檔案
        });
        ...
    
    }
  • 然後還要在我們的控制器上面標註swagger檔案的版本

    這時候我們就可以將介面檔案進行分組顯示了

4、API隱藏

  • 建立自定義隱藏特性 HiddenApiAttribute.cs
    /// 
    /// 隱藏swagger介面特性標識
    /// 

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class HiddenApiAttribute:System.Attribute
{
}

  • 建立API隱藏過濾器 HiddenApiFilter 繼承 Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter 介面,實現 Apply 方法
    /// 
    /// 自定義Swagger隱藏過濾器
    /// 

public class HiddenApiFilter : IDocumentFilter
{
public void Apply(SwaggerDocument 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.cs 中使用 HiddenApiFilter
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "介面檔案",
                Description =  "介面檔案-基礎",
                TermsOfService = "",
                Contact = new Contact
                {
                    Name = "XXX1111",
                    Email = "XXX1111@qq.com",
                    Url = ""
                }
            });
    
            c.SwaggerDoc("v2", new Info
            {
                Version = "v2",
                Title = "介面檔案",
                Description =  "介面檔案-基礎",
                TermsOfService = "",
                Contact = new Contact
                {
                    Name = "XXX2222",
                    Email = "XXX2222@qq.com",
                    Url = ""
                }
            });
    
            //反射註入全部程式集說明
            GetAllAssemblies().Where(t => t.CodeBase.EndsWith("Controller.dll")
                && !t.CodeBase.Contains("Common.Controller.dll")).ToList().ForEach(assembly =>
                {
                    c.IncludeXmlComments(assembly.CodeBase.Replace(".dll", ".xml"));
                });
    
            c.OperationFilter();
            c.DocumentFilter();
        });
        ...
    }
  • 示例:
    我這裡提供了Consul的心跳檢車介面

    但是在介面檔案中並沒有顯示出來

原文地址:https://www.cnblogs.com/wyt007/p/10650974.html

贊(0)

分享創造快樂