Skip to content

Commit

Permalink
feat: 新增 控制器文档排序 以及 授权存储
Browse files Browse the repository at this point in the history
  • Loading branch information
jianxuanbing committed May 13, 2020
1 parent ce43ce5 commit e42c7bd
Show file tree
Hide file tree
Showing 10 changed files with 180 additions and 18 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ Bing.Extensions.Swashbuckle是扩展Swashbuckle.AspNetCore一些常用操作,
- 支持显示枚举描述
- 支持Swagger文档授权登录功能
- 支持默认值设置
- 支持控制器排序
- 支持Token令牌存储


## 依赖类库
Expand Down
9 changes: 7 additions & 2 deletions samples/Bing.Samples.Api/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
using System.Collections.Generic;
using System.IO;
using Bing.Swashbuckle;
using Bing.Swashbuckle.Filters.Documents;
using Bing.Swashbuckle.Filters.Schemas;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
Expand Down Expand Up @@ -88,10 +90,12 @@ public IServiceProvider ConfigureServices(IServiceCollection services)
//// 显示授权信息
//config.ShowAuthorizeInfo();
// 显示枚举描述
config.ShowEnumDescription();
// 控制器排序
config.OrderByController();
// 显示Url模式:首字母小写、首字母大写、全小写、全大写、默认
config.ShowUrlMode();
Expand Down Expand Up @@ -177,9 +181,10 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
config.InjectJavascript("resources/translator");
//config.InjectJavascript("/swagger/resources/export");
config.InjectStylesheet("resources/swagger-common");
// 使用默认SwaggerUI
config.UseDefaultSwaggerUI();
// 启用Token存储
config.UseTokenStorage("oauth2");
};
});
app.UseMvc(routes =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ protected virtual string FormatDescription(Type type)
var sb = new StringBuilder();
var result = Enum.GetDescriptions(type);
foreach (var item in result)
sb.AppendLine($"{item.Value} = {(string.IsNullOrEmpty(item.Description) ? item.Name : item.Description)}");
sb.Append($"{item.Value} = {(string.IsNullOrEmpty(item.Description) ? item.Name : item.Description)}{Environment.NewLine}");
return sb.ToString();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Bing.Swashbuckle.Core;
using Bing.Swashbuckle.Filters.Documents;
using Bing.Swashbuckle.Filters.Operations;
using Bing.Swashbuckle.Filters.Parameters;
using Bing.Swashbuckle.Filters.Schemas;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
Expand All @@ -15,18 +16,39 @@ namespace Bing.Swashbuckle
/// </summary>
public static class SwaggerGenExtensions
{
#region ShowEnumDescription(显示枚举描述)

/// <summary>
/// 显示枚举描述
/// </summary>
/// <param name="options">Swagger生成选项</param>
public static void ShowEnumDescription(this SwaggerGenOptions options)
{
if (!options.ParameterFilterDescriptors.Exists(x => x.Type == typeof(EnumDescriptionsDocumentFilter)))
options.ParameterFilter<EnumDescriptionsDocumentFilter>();
if (!options.ParameterFilterDescriptors.Exists(x => x.Type == typeof(EnumDescriptionsParameterFilter)))
options.ParameterFilter<EnumDescriptionsParameterFilter>();
if (!options.SchemaFilterDescriptors.Exists(x => x.Type == typeof(EnumDescriptionSchemaFilter)))
options.SchemaFilter<EnumDescriptionSchemaFilter>();
}

#endregion

#region OrderByController(基于控制器进行排序)

/// <summary>
/// 基于控制器进行排序
/// </summary>
/// <param name="options">Swagger生成选项</param>
/// <param name="orderByDesc">是否降序排序</param>
public static void OrderByController(this SwaggerGenOptions options, bool orderByDesc = false)
{
if (!options.DocumentFilterDescriptors.Exists(x => x.Type == typeof(TagReOrderDocumentFilter)))
options.DocumentFilter<TagReOrderDocumentFilter>(orderByDesc);
}

#endregion



/// <summary>
/// 显示文件参数
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,25 @@ public static void UseCustomSwaggerIndex(this SwaggerUIOptions options)

#endregion

#region UseTokenStorage(使用令牌存储)

/// <summary>
/// 使用令牌存储。解决刷新页面导致令牌丢失问题,前提必须使用 <see cref="UseCustomSwaggerIndex"/> 方法
/// </summary>
/// <param name="options">SwaggerUI选项</param>
/// <param name="securityDefinition">授权定义。对应于 AddSecurityDefinition 中的 name</param>
/// <param name="cacheType">缓存类型</param>
public static void UseTokenStorage(this SwaggerUIOptions options, string securityDefinition, WebCacheType cacheType = WebCacheType.Session)
{
options.ConfigObject.AdditionalItems["token_storage"] = new TokenStorageParameter
{
CacheType = cacheType,
SecurityDefinition = securityDefinition
};
}

#endregion

/// <summary>
/// 添加信息
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.Linq;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Bing.Swashbuckle.Filters.Documents
{
/// <summary>
/// 标识重新排序 文档过滤器。用于对控制器进行排序
/// </summary>
internal class TagReOrderDocumentFilter : IDocumentFilter
{
/// <summary>
/// 是否降序排序
/// </summary>
private readonly bool _orderByDesc;

/// <summary>
/// 初始化一个<see cref="TagReOrderDocumentFilter"/>类型的实例
/// </summary>
/// <param name="orderByDesc">是否降序排序</param>
public TagReOrderDocumentFilter(bool orderByDesc = false) => _orderByDesc = orderByDesc;

/// <summary>
/// 重写操作处理
/// </summary>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Tags = _orderByDesc
? swaggerDoc.Tags.OrderByDescending(tag => tag.Name).ToList()
: swaggerDoc.Tags.OrderBy(tag => tag.Name).ToList();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
using Microsoft.OpenApi.Models;
using System;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Bing.Swashbuckle.Filters.Documents
namespace Bing.Swashbuckle.Filters.Parameters
{
/// <summary>
/// 枚举描述 文档过滤器。支持Url查询参数
/// 枚举描述 参数过滤器。支持Url查询参数
/// </summary>
internal class EnumDescriptionsDocumentFilter : EnumHandleBase, IParameterFilter
internal class EnumDescriptionsParameterFilter : EnumHandleBase, IParameterFilter
{
/// <summary>
/// 重写操作处理
Expand All @@ -16,10 +17,8 @@ public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
var type = context.ParameterInfo?.ParameterType;
if (type == null)
return;
if (type.IsEnum)
{
parameter.Description = $"{parameter.Description}\r\n{FormatDescription(type)}";
}
if (type.IsEnum)
parameter.Description = $"{parameter.Description}{Environment.NewLine}{FormatDescription(type)}";
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.OpenApi.Models;
using System;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Bing.Swashbuckle.Filters.Schemas
Expand All @@ -14,9 +15,7 @@ internal class EnumDescriptionSchemaFilter : EnumHandleBase, ISchemaFilter
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (context.Type.IsEnum)
{
schema.Description = $"{schema.Description}\r\n{FormatDescription(context.Type)}";
}
schema.Description = $"{schema.Description}{Environment.NewLine}{FormatDescription(context.Type)}";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@
window.onload = function () {
var configObject = JSON.parse('%(ConfigObject)');
var oauthConfigObject = JSON.parse('%(OAuthConfigObject)');

console.log('configObject', configObject);
console.log('oauthConfigObject', oauthConfigObject);

// Apply mandatory parameters
configObject.dom_id = "#swagger-ui";
configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
Expand All @@ -98,9 +102,13 @@
if (!configObject.hasOwnProperty("oauth2RedirectUrl"))
//configObject.oauth2RedirectUrl = window.location + "oauth2-redirect.html"; // use the built-in default
configObject.oauth2RedirectUrl = window.location.href.replace("index.html", "oauth2-redirect.html");

// 初始化Token存储
initTokenStorage(configObject);

// Build a system
const ui = SwaggerUIBundle(configObject);
const ui = SwaggerUIBundle(configObject);
window.ui = ui;

// Apply OAuth config
ui.initOAuth(oauthConfigObject);
Expand Down Expand Up @@ -142,6 +150,48 @@
document.getElementsByClassName('topbar-wrapper')[0].appendChild(logOutEle)
}
}

function initTokenStorage(configObject) {
if(!configObject.token_storage)
return;
configObject.onComplete= () => {
var result = (localStorage.getItem(configObject.token_storage.securityDefinition)) || (sessionStorage.getItem(configObject.token_storage.securityDefinition));
ui.preauthorizeApiKey(configObject.token_storage.securityDefinition, result);
};
configObject.requestInterceptor = (req) => {
req.headers["Authorization"] = (localStorage.getItem(configObject.token_storage.securityDefinition)) || (sessionStorage.getItem(configObject.token_storage.securityDefinition));
return req;
};
addAuthorizeListener(configObject);
}

function addAuthorizeListener(configObject) {
var authWrapper = document.querySelector(".scheme-container .auth-wrapper");
if(authWrapper === undefined || authWrapper === null){
setTimeout(function(){
addAuthorizeListener(configObject);
}, 3000);
return;
}
console.log("初始化存储 Token 监听处理");
authWrapper.addEventListener("click", function(e){
if(e.type === "click" && e.srcElement.tagName === "BUTTON") {
if(e.srcElement.innerText === "Authorize") {
var result = document.querySelector(".auth-container .wrapper input").value;
console.log(result);
if(configObject.token_storage.cacheType === "Local")
localStorage.setItem(configObject.token_storage.securityDefinition, result);
else
sessionStorage.setItem(configObject.token_storage.securityDefinition, result);
} else if(e.srcElement.innerText === "Logout") {
if(configObject.token_storage.cacheType === "Local")
localStorage.removeItem(configObject.token_storage.securityDefinition);
else
sessionStorage.removeItem(configObject.token_storage.securityDefinition);
}
}
}, false);
}
</script>
</body>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
namespace Bing.Swashbuckle
{
/// <summary>
/// 令牌存储参数。用于拦截登录后存储令牌,解决刷新页面导致令牌丢失问题
/// </summary>
internal class TokenStorageParameter
{
/// <summary>
/// 授权定义。对应于 AddSecurityDefinition 中的 name
/// </summary>
public string SecurityDefinition { get; set; }

/// <summary>
/// 网页缓存类型
/// </summary>
public WebCacheType CacheType { get; set; }
}

/// <summary>
/// 网页缓存方式
/// </summary>
public enum WebCacheType
{
/// <summary>
/// 本地存储
/// </summary>
Local,
/// <summary>
/// 会话
/// </summary>
Session,
}
}

0 comments on commit e42c7bd

Please sign in to comment.