.NET Core Swagger 的分组使, 以及相同Action能被多个分组公用,同时加载出尚未分组的数据出来
.NET Core Swagger 的分组使, 以及相同Action能被多个分组公用,同时加载出尚未分组的数据出来
1.本文章参考(https://www.cnblogs.com/caijt/p/10739841.html)改写的 一对多分组模式。需要一对一的可以参考
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).OfTypeGroupInfoAttribute().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.0Configure里面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).OfTypeGroupInfoAttribute().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 ILoggerWeatherForecastController _logger; private readonly IHttpContextAccessor _accessor; public WeatherForecastController(ILoggerWeatherForecastController 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能被多个分组公用,同时加载出尚未分组的数据出来 相关文章
- ASP.NET Core Web主机(IWebHostBuilder)
1.前言 ASP.NET Core应用程序可以配置和启动主机(Host)。主机负责应用程序启动和生存期管理,配置服务器和请求处理管道。主机还可以设置日志记录、依赖关系注入和配置。而host主机又包括Web主机(IWebHostBuilder)和通用主机(IHostBuilder)。该章节主要
- 在Asp.Net Core Web API中使用JWT鉴权(2)使用JWT鉴权
本文承接上一篇在Asp.Net Core Web API中使用JWT鉴权(1)创建鉴权中心。 1、创建Asp.Net Core Web API项目 这里使用的环境是VS2019 + .Net Core 3.1。 2、在Startup中注册JWT鉴权 (1) 使用Nuget安装Microsoft.AspNetCore.Authentication.JwtBearer。 (2) 注册
- cad.net 替换Polyline2d的点
Polyline2d的点更改,它和其他的图元处理起来不一样,因为它是一个复杂实体. 需要通过枚举值来处理. 提取点集 先看一个通用的提取点集的做法, GetStretchPoints可以作用在:轻多段线/二维多段线/三维多段线 你只需要将Polyline2d改成其他即可. 之所以改成ListPo
- .Net工作流elsa-workflows官方文档学习:工作流相关概念
网页:https://elsa-workflows.github.io/elsa-core/docs/concepts-workflows 工作流(Workflow) 工作流由一系列步骤组成,这些步骤称为活动(Activity)。工作流维护各种信息,例如: 当前正在执行哪个活动 设置了哪些变量 哪些活动阻塞了执行 一个活动完
- ASP.NET Core获取请求完整的Url
在ASP.NET项目中获取请求完整的Url: 获取System.Web命名空间下的类名为HttpRequestBase的Url方法: /// summary在派生类中替代时,获取有关当前请求的 URL 的信息。/summary /// returns包含有关当前请求的 URL 的信息的对象。/returns /// exception cref=
- .Net工作流elsa-workflows官方文档学习:安装Elsa设计器
网页:https://elsa-workflows.github.io/elsa-core/docs/installing-elsa-designer Elsa仪表盘已包含设计器,本节主要是为了帮助那些想自己实现设计器的人。 最简单方法是在HTML文档中包含以下内容: script src='https://unpkg.com/@elsa-workflows/elsa-w
- ASP.NET Core WebApi版本控制
前言: 在日常项目开发中,随着项目需求不断的累加、不断的迭代;项目服务接口需要向下兼容历史版本;前些时候就因为Api接口为做版本管理导致接口对低版本兼容处理不友好。 最近就像了解下如何实现WebApi版本控制,那么版本控制有什么好处呢 WebApi版本控制
- .net5 core webapi进阶之一:System.Text.Json的用法详解
从本篇开始写 .net5 core webapi 进阶系列,先从JSON这种数据格式开始,原因如下: 1 . 够简洁; 2 . 易于理解; 3 . 其格式和面向对象的语言天然匹配; 4 . 多语言(Javascript 、C# 、Java 等)支持; 毫无疑问,JSON是不同语言,不同系统之间进行数据交换
- .Net工作流elsa-workflows官方文档学习:安装Elsa持久性提供程序
网页:https://elsa-workflows.github.io/elsa-core/docs/installing-persistence 工作流默认存储在内存中,也可以添加其它持久性提供程序。 使用实体框架(Entity Framework) 如果使用Entity Framework Core持久性提供程序并使用Sqlite数据库,请添加以下
- ASP.NET Core 跨域
跨域常见问题: 1.发布到IIS上后跨域问题 解决方法 修改web.config文件 system.webServer httpProtocol customHeaders add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" / add name="Access-Control-Allow-Headers" value="con