ASP.NET Core學習之九 swagger接口文檔

介紹

https://github.com/domaindrivendev/Swashbuckle.AspNetCore

https://github.com/swagger-api/swagger-ui

集成swagger

引用Swashbuckle

新建一個restfull api項目,版本爲.NET CORE 3.1,
使用nuget添加Swashbuckle.AspNetCore,當前版本爲6.2.2

添加並配置 Swagger 中間件

修改Startup類的ConfigureServices方法

//註冊Swagger生成器,定義一個和多個Swagger 文檔
services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});

Configure方法

//啓用中間件服務生成Swagger作爲JSON終結點
app.UseSwagger();
//啓用中間件服務對swagger-ui,指定Swagger JSON終結點
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

到此配置結束,啓動應用,訪問http://localhost:/swagger/index.html查看

添加接口說明

啓用XML註釋:
右鍵單擊“解決方案資源管理器”中的項目,然後選擇“屬性”,
查看“生成”選項卡的“輸出”部分下的“XML 文檔文件”框勾選上

修改Startup類的ConfigureServices方法

app.UseSwaggerUI(c =>
{
    .....此處省略
  var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
  var xmlPath = Path.Combine(basePath, "SwaggerApi.xml");
  c.IncludeXmlComments(xmlPath);
});

在方法上註釋

/// <summary>
/// Get方法
/// </summary>
/// <returns></returns>

參考文檔

https://cloud.tencent.com/developer/article/1339371
https://www.cnblogs.com/yilezhu/p/9241261.html

ABP集成MagicodesSwagger

環境

.NET CORE 3.1.0

配置文件

appsettings.json增加節點

  "SwaggerDoc": {
    "IsEnabled": "true",
    //將枚舉值以字符串顯示
    "DescribeAllEnumsAsStrings": false,
    "SwaggerDocInfos": [
      {
        "IsEnabled": "true",
        "Title": "管理平臺 API文檔",
        "Version": "v1",
        "GroupName": "admin",
        "Description": "",
        "GroupUrlPrefix": "admin/"
      }
    ],
    "HiddenApi": {
      "IsEnabled": "true",
      "Urls": [
        { "Url": "app1/Values/{id}" }
      ]
    },
    "UseFullNameForSchemaId": "false"
  }

Startup.cs

 public IServiceProvider ConfigureServices(IServiceCollection services)
        { 
            ......此處省略
            //線上發佈版,不配置
            if (!_environment.IsProduction())
            {
                services.AddMagicodesSwaggerGen(_appConfig);
                services.AddSwaggerGen(options =>
                {
                    options.CustomSchemaIds(r => r.FullName);
                    //options.DocumentFilter<ApplyTagDescriptions>();//模塊說明 
                }); 
            }
			
		 return services.AddAbp<ECMWebModule>(options =>
            {
                //Configure Log4Net logging
                options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                   f => f.UseAbpLog4Net().WithConfig("log4net.config")
               );
            }, 0);
            //return services.BuildServiceProvider();
        }
		
        /// <summary>
        /// 負責http請求管道的配置
        /// </summary>
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IWebHostEnvironment env)
        { 
            ......此處省略
            //線上發佈版,不配置 ==> 一定要放在app.UseStaticFiles();之前,否則會出錯
            if (!env.IsProduction())
            {
                app.UseMagicodesSwaggerUI(_appConfig, (options, config) =>
                {
                    options.RoutePrefix = string.Empty;
                    options.ShowExtensions();
                    options.EnableValidator();
                    // 將選擇的接口地址連接到URL,方便與他人定位
                    //options.EnableDeepLinking();
                    // 啓用過濾器(大小寫敏感)
                    options.EnableFilter();
                    // 展開級別
                    //options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
                    // 右側顯示方法名
                    //options.DisplayOperationId();

                    /* 啓用下面代碼,生成適合用於對接的Swagger頁面 */
                    // 默認顯示model
                    //options.DefaultModelRendering(Swashbuckle.AspNetCore.SwaggerUI.ModelRendering.Model);
                    // 模型展開到2級
                    options.DefaultModelExpandDepth(3);
                    // 隱藏model列表
                    //options.DefaultModelsExpandDepth(-1);
                    // 隱藏 [Try it]
                    //options.SupportedSubmitMethods();
                });
            }
 
            app.UseStaticFiles();
            ......此處省略

        }	
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章