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();
            ......此处省略

        }	
原文地址:https://www.cnblogs.com/xcsn/p/15411260.html