最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Asp.Net Core WebAPI使用Swagger時(shí)API隱藏和分組詳解

 更新時(shí)間:2019年04月04日 10:23:38   作者:進(jìn)擊的辣條  
這篇文章主要給大家介紹了關(guān)于Asp.Net Core WebAPI使用Swagger時(shí)API隱藏和分組的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Asp.Net Core具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

1、前言

為什么我們要隱藏部分接口?

因?yàn)槲覀冊(cè)谟胹wagger代替接口的時(shí)候,難免有些接口會(huì)直觀的暴露出來(lái),比如我們結(jié)合Consul一起使用的時(shí)候,會(huì)將健康檢查接口以及報(bào)警通知接口暴露出來(lái),這些接口有時(shí)候會(huì)出于方便考慮,沒(méi)有進(jìn)行加密,這個(gè)時(shí)候我們就需要把接口隱藏起來(lái),只有內(nèi)部的開(kāi)發(fā)者知道。

為什么要分組?

通常當(dāng)我們寫(xiě)前后端分離的項(xiàng)目的時(shí)候,難免會(huì)遇到編寫(xiě)很多接口供前端頁(yè)面進(jìn)行調(diào)用,當(dāng)接口達(dá)到幾百個(gè)的時(shí)候就需要區(qū)分哪些是框架接口,哪些是業(yè)務(wù)接口,這時(shí)候給swaggerUI的接口分組是個(gè)不錯(cuò)的選擇。

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

2、swaggerUI中加入授權(quán)請(qǐng)求

新建HttpHeaderOperationFilter操作過(guò)濾器,繼承Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter接口,實(shí)現(xiàn)Apply方法

/// <summary>
/// swagger請(qǐng)求頭
/// </summary>
public class HttpHeaderOperationFilter : IOperationFilter
{
 public void Apply(Operation operation, OperationFilterContext context)
 {
  #region 新方法
  if (operation.Parameters == null)
  {
   operation.Parameters = new List<IParameter>();
  }

  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 = "header",
     Type = "string",
     Required = true,
     Description = "請(qǐng)輸入Token,格式為bearer XXX"
    });
   }
  }
  #endregion

  #region 已過(guò)時(shí)
  //if (operation.Parameters == null)
  //{
  // operation.Parameters = new List<IParameter>();
  //}
  //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 = "header",
  //  Type = "string",
  //  Required = true,
  //  Description = "請(qǐng)輸入Token,格式為bearer XXX"
  // });
  //}
  #endregion
 }
}

然后修改Startup.cs中的ConfigureServices方法,添加我們自定義的HttpHeaderOperationFilter過(guò)濾器

public IServiceProvider ConfigureServices(IServiceCollection services)
{
 ...
 services.AddSwaggerGen(c =>
 {
  ...
  c.OperationFilter<HttpHeaderOperationFilter>();
 });
 ...
}

這時(shí)候我們?cè)僭L問(wèn)swaggerUI就可以輸入Token了

3、API分組

修改Startup.cs中的ConfigureServices方法,添加多個(gè)swagger文檔

public IServiceProvider ConfigureServices(IServiceCollection services)
{
 ...
 services.AddSwaggerGen(c =>
 {
  c.SwaggerDoc("v1", new Info
  {
   Version = "v1",
   Title = "接口文檔",
   Description = "接口文檔-基礎(chǔ)",
   TermsOfService = "",
   Contact = new Contact
   {
    Name = "XXX1111",
    Email = "XXX1111@qq.com",
    Url = ""
   }
  });

  c.SwaggerDoc("v2", new Info
  {
   Version = "v2",
   Title = "接口文檔",
   Description = "接口文檔-基礎(chǔ)",
   TermsOfService = "",
   Contact = new Contact
   {
    Name = "XXX2222",
    Email = "XXX2222@qq.com",
    Url = ""
   }
  });

  //反射注入全部程序集說(shuō)明
  GetAllAssemblies().Where(t => t.CodeBase.EndsWith("Controller.dll")).ToList().ForEach(assembly =>
   {
    c.IncludeXmlComments(assembly.CodeBase.Replace(".dll", ".xml"));
   });

  c.OperationFilter<HttpHeaderOperationFilter>();
  //c.DocumentFilter<HiddenApiFilter>();
 });
 ...
}

修改Startup.cs中的Configure方法,加入

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
 ...
 app.UseSwagger();
 app.UseSwaggerUI(c =>
 {
  c.SwaggerEndpoint("/swagger/v2/swagger.json", "接口文檔-基礎(chǔ)");//業(yè)務(wù)接口文檔首先顯示
  c.SwaggerEndpoint("/swagger/v1/swagger.json", "接口文檔-業(yè)務(wù)");//基礎(chǔ)接口文檔放后面后顯示
  c.RoutePrefix = string.Empty;//設(shè)置后直接輸入IP就可以進(jìn)入接口文檔
 });
 ...

}

然后還要在我們的控制器上面標(biāo)注swagger文檔的版本

這時(shí)候我們就可以將接口文檔進(jìn)行分組顯示了

4、API隱藏

創(chuàng)建自定義隱藏特性HiddenApiAttribute.cs

/// <summary>
/// 隱藏swagger接口特性標(biāo)識(shí)
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class HiddenApiAttribute:System.Attribute
{
}

創(chuàng)建API隱藏過(guò)濾器HiddenApiFilter繼承Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter接口,實(shí)現(xiàn)Apply方法

/// <summary>
/// 自定義Swagger隱藏過(guò)濾器
/// </summary>
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 = "接口文檔-基礎(chǔ)",
   TermsOfService = "",
   Contact = new Contact
   {
    Name = "XXX1111",
    Email = "XXX1111@qq.com",
    Url = ""
   }
  });

  c.SwaggerDoc("v2", new Info
  {
   Version = "v2",
   Title = "接口文檔",
   Description = "接口文檔-基礎(chǔ)",
   TermsOfService = "",
   Contact = new Contact
   {
    Name = "XXX2222",
    Email = "XXX2222@qq.com",
    Url = ""
   }
  });

  //反射注入全部程序集說(shuō)明
  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<HttpHeaderOperationFilter>();
  c.DocumentFilter<HiddenApiFilter>();
 });
 ...
}

示例:

我這里提供了Consul的心跳檢車(chē)接口

但是在接口文檔中并沒(méi)有顯示出來(lái)

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

  • asp.net下大文件上傳知識(shí)整理

    asp.net下大文件上傳知識(shí)整理

    asp.net下大文件上傳知識(shí)整理...
    2007-03-03
  • 詳解ASP.NET提取多層嵌套json數(shù)據(jù)的方法

    詳解ASP.NET提取多層嵌套json數(shù)據(jù)的方法

    本篇文章主要介紹了ASP.NET提取多層嵌套json數(shù)據(jù)的方法,利用第三方類(lèi)庫(kù)Newtonsoft.Json提取多層嵌套json數(shù)據(jù)的方法,有興趣的可以了解一下。
    2017-02-02
  • log4net教程日志分類(lèi)和自動(dòng)維護(hù)示例

    log4net教程日志分類(lèi)和自動(dòng)維護(hù)示例

    log4net能不能按照功能分類(lèi)呢?如果通過(guò)配置不同的logger,然后功能根據(jù)不同的LoggerName加載Ilog實(shí)例,是可以做到。但由于這些功能的log配置差異性極小,也許僅僅就是文件名不同。于是想通過(guò)代碼進(jìn)行配置,下面把方法分享如下
    2014-01-01
  • ASP.NET 路徑問(wèn)題的解決方法

    ASP.NET 路徑問(wèn)題的解決方法

    相對(duì)路徑和絕對(duì)路徑在ASP.NET中可以用~/來(lái)解決.
    2009-06-06
  • .net MVC使用Session驗(yàn)證用戶(hù)登錄(4)

    .net MVC使用Session驗(yàn)證用戶(hù)登錄(4)

    這篇文章主要為大家詳細(xì)介紹了.net MVC使用Session驗(yàn)證用戶(hù)登錄的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • ASP.NET使用Global.asax的方法

    ASP.NET使用Global.asax的方法

    Global.asax是ASP.NET Web應(yīng)用程序的全局文件,它包含了應(yīng)用程序級(jí)別的事件處理程序,允許開(kāi)發(fā)人員在應(yīng)用程序的生命周期中執(zhí)行特定的邏輯,本文介紹了如何使用Global.asax文件來(lái)增強(qiáng)ASP.NET Web應(yīng)用程序的功能,感興趣的朋友一起看看吧
    2024-03-03
  • linq中的轉(zhuǎn)換操作符

    linq中的轉(zhuǎn)換操作符

    這篇文章介紹了linq中的轉(zhuǎn)換操作符,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-03-03
  • asp.net圖片上傳實(shí)例

    asp.net圖片上傳實(shí)例

    網(wǎng)站后臺(tái)都需要有上傳圖片的功能,下面的例子就是實(shí)現(xiàn)有關(guān)圖片上傳。缺點(diǎn):圖片上傳到本服務(wù)器上,不適合大量圖片上傳
    2013-12-12
  • 基于ASP.NET Core數(shù)據(jù)保護(hù)生成驗(yàn)證token示例

    基于ASP.NET Core數(shù)據(jù)保護(hù)生成驗(yàn)證token示例

    本篇文章主要介紹了基于ASP.NET Core數(shù)據(jù)保護(hù)生成驗(yàn)證token,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-02-02
  • asp.net html控件的File控件實(shí)現(xiàn)多文件上傳實(shí)例分享

    asp.net html控件的File控件實(shí)現(xiàn)多文件上傳實(shí)例分享

    asp.net中html控件的File控件實(shí)現(xiàn)多文件上傳簡(jiǎn)單實(shí)例,開(kāi)發(fā)工具vs2010使用c#語(yǔ)言,感興趣的朋友可以了解下,必定是多文件上傳值得學(xué)習(xí),或許本文所提供的知識(shí)點(diǎn)對(duì)你有所幫助
    2013-02-02

最新評(píng)論

泗洪县| 宜宾市| 邵武市| 阿拉尔市| 花垣县| 阿克陶县| 冀州市| 白银市| 柯坪县| 玛纳斯县| 阿拉尔市| 吉安市| 平凉市| 湘乡市| 天镇县| 石楼县| 南漳县| 洛阳市| 白城市| 四川省| 竹山县| 西乌| 璧山县| 涞源县| 清苑县| 伊宁市| 嘉祥县| 呼图壁县| 西乡县| 饶平县| 新河县| 峨眉山市| 内黄县| 聂拉木县| 雷山县| 淮南市| 南涧| 西峡县| 侯马市| 高州市| 顺昌县|