.NET Core Swagger 的分组使, 以及相同Action能被多个分组公用,同时加载出尚未分组的数据出来
1.本文章参考 点击链接跳转 改写的 一对多分组模式。需要一对一的可以参考
2.本文主要讲的是 一对多 分组公用, 同时把尚未分组的加载出来
3.效果演示GIF图:

具体操作代码如下:
1.在项目创建一个目录(ApiGroup),然后创建三个类,分别为ApiGroupAttribute.cs(控制器特性),ApiGroupNames.css(系统分组枚举),GroupInfoAttribute.cs(给系统分组枚举值增加相关信息的特性,这个主要是用于在Swagger分组时可关联Title,Version,Description值)

ApiGroupAttribute.cs代码如下
/// <summary>
/// 系统分组特性
/// </summary>
public class ApiGroupAttribute : Attribute
{
public ApiGroupAttribute(params ApiGroupNames[] name)
{
GroupName = name;
}
public ApiGroupNames[] GroupName { get; set; }
}
ApiGroupNames.cs代码如下
/// <summary>
/// 系统分组枚举值
/// </summary>
public enum ApiGroupNames
{
[GroupInfo(Title = "All", Description = "All接口", Version = "")]
All = 0,
[GroupInfo(Title = "尚未分组", Description = "尚未分组相关接口", Version = "")]
NoGroup = 1,
[GroupInfo(Title = "登录认证", Description = "登录认证相关接口", Version = "")]
Login = 2,
[GroupInfo(Title = "IT", Description = "登录认证相关接口", Version = "")]
It = 3,
[GroupInfo(Title = "人力资源", Description = "登录认证相关接口", Version = "")]
Hr = 4,
[GroupInfo(Title = "系统配置", Description = "系统配置相关接口", Version = "")]
Config = 5
}
GroupInfoAttribute.cs代码如下
public class GroupInfoAttribute : Attribute
{
public string Title { get; set; }
public string Version { get; set; }
public string Description { get; set; }
}
******** 打开Startup.cs文件修改ConfigureServices方法(为了方便查看,只列出关于Swagger分组的关键代码)*************
//1.0 ConfigureServices 里面swagger 的设置
#region swagger
var openApiInfo = new OpenApiInfo
{
Version = "v1",
Title = "WebApi",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = new Uri("https://www.cnblogs.com/goodluckily/"),
Contact = new OpenApiContact
{
Name = "雨太阳",
Email = string.Empty,
Url = new Uri("https://www.cnblogs.com/goodluckily/")
},
License = new OpenApiLicense
{
Name = "许可证名字",
Url = new Uri("https://www.cnblogs.com/goodluckily/")
}
};
services.AddSwaggerGen(c =>
{
#region 分组方案二
//遍历ApiGroupNames所有枚举值生成接口文档,Skip(1)是因为Enum第一个FieldInfo是内置的一个Int值
typeof(ApiGroupNames).GetFields().Skip(1).ToList().ForEach(f =>
{
//获取枚举值上的特性
var info = f.GetCustomAttributes(typeof(GroupInfoAttribute), false).OfType<GroupInfoAttribute>().FirstOrDefault();
openApiInfo.Title = info?.Title;
openApiInfo.Version = info?.Version;
openApiInfo.Description = info?.Description;
c.SwaggerDoc(f.Name, openApiInfo);
});
//判断接口归于哪个分组
c.DocInclusionPredicate((docName, apiDescription) =>
{
if (!apiDescription.TryGetMethodInfo(out MethodInfo method)) return false;
//1.全部接口
if (docName == "All") return true;
//反射拿到控制器分组特性下的值
var actionlist = apiDescription.ActionDescriptor.EndpointMetadata.FirstOrDefault(x => x is ApiGroupAttribute);
//2.得到尚未分组的接口***************
if (docName == "NoGroup") return actionlist == null ? true : false;
//3.加载对应已经分好组的接口
if (actionlist != null)
{
//判断是否包含这个分组
var actionfilter = actionlist as ApiGroupAttribute;
return actionfilter.GroupName.Any(x => x.ToString().Trim() == docName);
}
return false;
});
#endregion
//添加授权
//认证方式,此方式为全局添加
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, true);
});
#endregion
2.0 Configure 里面swagger 的设置
#region Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "swagger";
#region 分组方案二
//遍历ApiGroupNames所有枚举值生成接口文档,Skip(1)是因为Enum第一个FieldInfo是内置的一个Int值
typeof(ApiGroupNames).GetFields().Skip(1).ToList().ForEach(f =>
{
//获取枚举值上的特性
var info = f.GetCustomAttributes(typeof(GroupInfoAttribute), false).OfType<GroupInfoAttribute>().FirstOrDefault();
c.SwaggerEndpoint($"/swagger/{f.Name}/swagger.json", info != null ? info.Title : f.Name);
});
#endregion
//swagger 默认折叠
//c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
//MiniProfiler用的
c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("WebApi.index.html");
});
#endregion
然后你F6生成一下,没出错的话,就Ctrl+F5看看,正常的话就会在Swagger右上角看到分组了。

*********************具体在 WeatherForecastController 里面的使用***************
1.单个Action特性 [ApiGroup(ApiGroupNames.Config)]

2.多个Action特性 [ApiGroup(ApiGroupNames.Login,ApiGroupNames.It)]

..............
具体详细的Controller代码如下
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : Controller
{ private readonly ILogger<WeatherForecastController> _logger; private readonly IHttpContextAccessor _accessor;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IHttpContextAccessor accessor)
{
_logger = logger;
_accessor = accessor;
}
/// <summary>
/// 多分组共用请求
/// </summary>
/// <returns></returns>
//[ProducesResponseType(201)]
//[ProducesResponseType(400)] [HttpGet("getLoginAndIT")]
[ApiGroup(ApiGroupNames.Login,ApiGroupNames.It)]
public IActionResult GetLoginAndIT()
{
return Json("GetLoginAndIT ok");
} [HttpGet("getConfig")]
[ApiGroup(ApiGroupNames.Config)]
public IActionResult GetConfig()
{
return Json("Config ok");
} [HttpGet("getHr")]
[ApiGroup(ApiGroupNames.Hr)] public IActionResult GetHr()
{
return Json("Hr ok");
} [HttpGet("getIt")]
[ApiGroup(ApiGroupNames.It)] public IActionResult GetIt()
{
return Json("GetIt ok");
}
/// <summary>
/// 获取Miniprofiler Index的 Script (尚未分组的)
/// </summary>
/// <returns></returns>
[HttpGet("getMiniprofilerScript")]
public IActionResult getMiniprofilerScript()
{
var htmlstr = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext);
var script = htmlstr.Value;
return Json(script);
}
}
-----------至此结束 end ----------------------------------
有疑问意见等,欢迎大家讨论.......
.NET Core Swagger 的分组使, 以及相同Action能被多个分组公用,同时加载出尚未分组的数据出来的更多相关文章
- .NET Core配置文件加载与DI注入配置数据
.NET Core配置文件 在以前.NET中配置文件都是以App.config / Web.config等XML格式的配置文件,而.NET Core中建议使用以JSON为格式的配置文件,因为使用起来更 ...
- [转].NET Core配置文件加载与DI注入配置数据
本文转自:http://www.cnblogs.com/skig/p/6079187.html .NET Core配置文件 在以前.NET中配置文件都是以App.config / Web.config ...
- Web版RSS阅读器(二)——使用dTree树形加载rss订阅分组列表
在上一边博客<Web版RSS阅读器(一)——dom4j读取xml(opml)文件>中已经讲过如何读取rss订阅文件了.这次就把订阅的文件读取到页面上,使用树形结构进行加载显示. 不打算使用 ...
- 【ASP.NET Core】EF Core - “影子属性” 深入浅出经典面试题:从浏览器中输入URL到页面加载发生了什么 - Part 1
[ASP.NET Core]EF Core - “影子属性” 有朋友说老周近来博客更新较慢,确实有些慢,因为有些 bug 要研究,另外就是老周把部分内容转到直播上面,所以写博客的内容减少了一点. ...
- Asp.Net Core Swagger 接口分组(支持接口一对多暴露)
开始之前,先介绍下swagger常用方法. services.AddSwaggerGen //添加swagger中间件 c.SwaggerDoc //配置swagger文档,也就是右上角的下拉 ...
- EntityFramework Core饥饿加载忽略导航属性问题
前言 .NET Core项目利用EntityFramework Core作为数据访问层一直在进行中,一直没有过多的去关注背后生成的SQL语句,然后老大捞出日志文件一看,恩,有问题了,所以本文产生了,也 ...
- [翻译 EF Core in Action 2.4] 加载相关数据
Entity Framework Core in Action Entityframework Core in action是 Jon P smith 所著的关于Entityframework Cor ...
- 分享一个集成.NET Core+Swagger+Consul+Polly+Ocelot+IdentityServer4+Exceptionless+Apollo+SkyWalking的微服务开发框架
集成.NET Core+Swagger+Consul+Polly+Ocelot+IdentityServer4+Exceptionless+Apollo的微服务开发框架 Github源代码地址 htt ...
- .net core swagger汉化
基本swagger使用不再详解,具体百度其它帖子 1.将汉化的swagger js文件复制到项目根目录中 js代码如下 'use strict'; /** * Translator for docum ...
随机推荐
- SparkStreaming直连方式读取kafka数据,使用MySQL保存偏移量
SparkStreaming直连方式读取kafka数据,使用MySQL保存偏移量 1. ScalikeJDBC 2.配置文件 3.导入依赖的jar包 4.源码测试 通过MySQL保存kafka的偏移量 ...
- SpringBoot整合spring-security-oauth2完整实现例子
SpringBoot整合spring-security-oauth2完整实现例子 技术栈 : springboot + spring-security + spring-oauth2 + mybati ...
- 模块化之CommonJS
一.CommonJS特点 经过前面讨论,已经知道无模块化时项目中存在的问题.CommonJS的特点就是解决这些问题即: 1.每个文件都是一个单独的模块,有自己的作用域,声明的变量不是全局变量( ...
- 1155 Heap Paths
题干前半略. Sample Input 1: 8 98 72 86 60 65 12 23 50 Sample Output 1: 98 86 23 98 86 12 98 72 65 98 72 ...
- Codeforces Global Round 7 A. Bad Ugly Numbers(数学)
题意: 给你一个 n,输出一个 n 位不含 0 且不被任一位整除的正数. 思路: 构造 233 或 899. #include <bits/stdc++.h> using namespac ...
- Codeforces Round #651 (Div. 2) A Maximum GCD、B GCD Compression、C Number Game、D Odd-Even Subsequence
A. Maximum GCD 题意: t组输入,然后输入一个n,让你在区间[1,n]之间找出来两个不相等的数a,b.求出来gcd(a,b)(也就是a,b最大公约数).让你求出来最大的gcd(a,b)是 ...
- java——接口、多态性、对象转型
接口定义: 默认方法: 默认方法的作用: 如果在你的接口已经投入使用了,这个时候你想要在接口里面加一个方法,这个时候如果你加一个抽象方法的话,所有实现类都要改变源代码(因为实现类要把接口中的所有抽象 ...
- Codeforces #624 div3 C
You want to perform the combo on your opponent in one popular fighting game. The combo is the string ...
- Codeforces Round #666 (Div. 2) C. Multiples of Length (贪心)
题意:给你一个由\(0,1,?\)组成的字符串,你可以将\(?\)任意改成\(0\)或\(1\),问你操作后能否使得该字符串的任意长度为\(k\)的区间中的\(0\)和$1的个数相等. 题解:我们首先 ...
- Atcoder Educational DP Contest I - Coins (概率DP)
题意:有\(n\)枚硬币,每枚硬币抛完后向上的概率为\(p[i]\),现在求抛完后向上的硬币个数大于向下的概率. 题解:我们用二维的\(dp[i][j]\)来表示状态,\(i\)表示当前抛的是第\(i ...