(二)集成Swagger接口文档分组配置.net core

(一)回顾:

上一篇为大家介绍了在.NET Core中如何集成Swagger的介绍,想想集成操作其实非常简单便捷,实质就三个步骤:

(1)在项目中执行nuget命令,拉取Swagger包到项目:Install-package Swashbuckle.AspNetCore

(2)在ConfigureServices方法中新增如下代码

#region Swagger
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info
        {
            Version = "v1.1.0",
            Title = "Swagger WebAPI",
            Description = "XXX项目API文档",
            TermsOfService = "None",
            Contact = new Swashbuckle.AspNetCore.Swagger.Contact
            {
                Name = "XXX项目",
                Email = "273145719@qq.com"
            ,
                Url = "https://www.cnblogs.com/NBIDataVis/"
            }
        });
        // 为 Swagger JSON and UI设置xml文档注释路径
        var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
        var xmlPath = Path.Combine(basePath, "CoreWebAPI.xml");
        //如果需要显示控制器注释只需将第二个参数设置为true
        c.IncludeXmlComments(xmlPath, true);
    });
#endregion

(3)在Configure方法中新增如下代码

#region Swagger
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
      c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiDocument V1");
    });
#endregion

(二)问题:

通常一个项目中有很多的功能模块,每个功能模块又可能对应很多的接口,如果所有的接口都在一个列表显示,显然是比较混乱的,不便于调用方阅读和查找。

当然Swagger为我们已经考虑到了这一点,它能支持分组显示,具体怎么做呢,请看下面的配置:

(三)Swagger分组文档配置:

(1)在ConfigureServices方法中新增如下代码

#region Swagger
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info
        {
            Version = "v1.1.0",
            Title = "Swagger WebAPI",
            Description = "XXX项目API文档",
            TermsOfService = "None",
            Contact = new Swashbuckle.AspNetCore.Swagger.Contact
            {
                Name = "XXX项目",
                Email = "273145719@qq.com"
            ,
                Url = "https://www.cnblogs.com/NBIDataVis/"
            }
        });
        
        c.SwaggerDoc("User", new Info { Title = "用户模块", Version = "User" });   //分组显示
        c.SwaggerDoc("Project", new Info { Title = "项目模块", Version = "Project" });   //分组显示

        var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
        var xmlPath = Path.Combine(basePath, "CoreWebAPI.xml");
        c.IncludeXmlComments(xmlPath, true);
    
    });
#endregion

(2)在Configure方法中新增如下代码

#region Swagger
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
        c.SwaggerEndpoint("/swagger/User/swagger.json", "用户模块");  //分组显示
        c.SwaggerEndpoint("/swagger/Project/swagger.json", "项目模块");  //分组显示
    });
#endregion

(3)在Controller类上指定分组名:


 

(4)看看运行效果:

posted @ 2019-10-31 15:24  NBI大数据可视化分析  阅读(834)  评论(0编辑  收藏  举报