Asp.Net Core Swagger Api 分组和控制器注释

为什么要使用Api分组

  1. 同一个项目各端接口分离
  2. 前端更好的查询各端Api接口
  3. 后端更好的管理接口分组

本文使用的是.Net6项目

项目地址

地址

代码

新建SwaggerExtensions.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lotus.Blog.TNT.Swagger
{
    public static class SwaggerExtensions
    {

        /// <summary>
        /// Api版本号
        /// </summary>
        public static string version = "1.0.0";
        /// <summary>
        /// 分组
        /// </summary>
        public static class Grouping
        {
            /// <summary>
            /// 博客前台接口组
            /// </summary>
            public const string GroupName_v1 = "v1";

            /// <summary>
            /// 博客后台接口组
            /// </summary>
            public const string GroupName_v2 = "v2";

            /// <summary>
            /// 其他通用接口组
            /// </summary>
            public const string GroupName_v3 = "v3";

            /// <summary>
            /// JWT授权接口组
            /// </summary>
            public const string GroupName_v4 = "v4";
        }
        private static readonly List<SwaggerApiInfo> ApiInfos = new List<SwaggerApiInfo>()
        {
            new SwaggerApiInfo
            {
                UrlPrefix = Grouping.GroupName_v1,
                Name = "博客前台接口",
                OpenApiInfo = new OpenApiInfo
                {
                    Version = version,
                    Title = "博客前台接口",
                    Description = ""
                }
            },
            new SwaggerApiInfo
            {
                UrlPrefix = Grouping.GroupName_v2,
                Name = "博客后台接口",
                OpenApiInfo = new OpenApiInfo
                {
                    Version = version,
                    Title = "博客后台接口",
                    Description = ""
                }
            },
            new SwaggerApiInfo
            {
                UrlPrefix = Grouping.GroupName_v3,
                Name = "通用公共接口",
                OpenApiInfo = new OpenApiInfo
                {
                    Version = version,
                    Title = "通用公共接口",
                    Description = ""
                }
            },
            new SwaggerApiInfo
            {
                UrlPrefix = Grouping.GroupName_v4,
                Name = "JWT授权接口",
                OpenApiInfo = new OpenApiInfo
                {
                    Version = version,
                    Title = "JWT授权接口",
                    Description = ""
                }
            }
        };


        public static void AddSwaggerUI(this IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                var xmlFiles = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.XML");
                foreach (var file in xmlFiles)
                {
                    options.IncludeXmlComments(file);

                }
               

                ApiInfos.ForEach(x =>
                {
                    options.SwaggerDoc(x.UrlPrefix, x.OpenApiInfo);
                });
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer",
                    BearerFormat = "JWT",
                    In = ParameterLocation.Header,
                    Description = "JWT token Bearer"
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });

            });
        }
        public static void UseSwaggerUI(this IApplicationBuilder app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                ApiInfos.ForEach(x =>
                {
                    options.SwaggerEndpoint($"/swagger/{x.UrlPrefix}/swagger.json", x.Name);
                });

                // 模型的默认扩展深度,设置为 -1 完全隐藏模型
                options.DefaultModelsExpandDepth(-1);
                //// API文档仅展开标记
                options.DocExpansion(DocExpansion.List);
                options.RoutePrefix = string.Empty;
                //// API前缀设置为空
                options.DocumentTitle = "忘忧小站";
            });
        }
    }
}

SwaggerApiInfo.cs

using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lotus.Blog.TNT.Swagger
{
    internal class SwaggerApiInfo
    {
        /// <summary>
        /// URL前缀
        /// </summary>
        public string UrlPrefix { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// <see cref="Microsoft.OpenApi.Models.OpenApiInfo"/>
        /// </summary>
        public OpenApiInfo OpenApiInfo { get; set; }
    }
}

如何使用
image.png

[ApiExplorerSettings(GroupName = SwaggerExtensions.Grouping.GroupName_v2)]

Program.cs使用

注意! 如果不是.Net项目 需要在startup.cs 文件中注册
image.png
image.png

实现效果
image.png
这样就达到了Swagger分组,将各个端接口分离开来,方便前端开发工程师查询

Swagger Controller 注释

SwaggerExtensions.cs 文件中修改代码
image.png

            var xmlFiles = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.XML");
                foreach (var file in xmlFiles)
                {
                    if (file.Contains("Lotus.Blog.Api.xml"))
                    {
                        options.IncludeXmlComments(file,true);
                    }
                    else
                    {
                        options.IncludeXmlComments(file, true);
                    }

                }
               

Logtus.Blog.Api.xml 为你Controller项目的名称

Controller增加注释
image.png
实现效果
image.png

总结

至此该篇文章结束

# Swagger  Core  Asp.Net 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×