Skip to content

Commit

Permalink
feat: 更新Swagger相关内容,适配官方最新异步版本 (#543)
Browse files Browse the repository at this point in the history
  • Loading branch information
joesdu authored Sep 23, 2024
2 parents b42ecc0 + 91b8254 commit 9660388
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 60 deletions.
2 changes: 1 addition & 1 deletion sample/WebApi.Test.Unit/WebApi.Test.Unit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Map" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.OpenTelemetry" Version="4.1.1-dev-00351" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.7.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.8.0" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
<PackageVersion Include="RabbitMQ.Client" Version="7.0.0-rc.11" />
<PackageVersion Include="Serilog" Version="4.0.2-dev-02226" />
<PackageVersion Include="Spectre.Console.Json" Version="0.49.2-preview.0.44" />
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.7.3" />
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.7.3" />
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.8.0" />
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.8.0" />
<!--microsoft asp.net core -->
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.0-rc.1.24431.7" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0-rc.1.24431.7" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,38 @@ namespace EasilyNET.WebCore.Swagger.SwaggerFilters;
/// </summary>
// ReSharper disable once UnusedMember.Global
// ReSharper disable once ClassNeverInstantiated.Global
public sealed class SwaggerAuthorizeFilter : IOperationFilter
public sealed class SwaggerAuthorizeFilter : IOperationAsyncFilter
{
/// <summary>
/// Apply
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(OpenApiOperation operation, OperationFilterContext context)
/// <inheritdoc />
public async Task ApplyAsync(OpenApiOperation operation, OperationFilterContext context, CancellationToken cancellationToken)
{
var authAttributes = context.MethodInfo.DeclaringType?.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<AuthorizeAttribute>();
if (!authAttributes!.Any()) return;
operation.Security =
[
new()
{
await Task.Run(() =>
{
var authAttributes = context.MethodInfo.DeclaringType?.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<AuthorizeAttribute>();
if (!authAttributes!.Any()) return;
operation.Security =
[
new()
{
new()
{
Reference = new()
new()
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
Reference = new()
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List<string>()
new List<string>()
}
}
}
];
operation.Responses.Add("401", new() { Description = "Unauthorized" });
];
operation.Responses.Add("401", new() { Description = "Unauthorized" });
}, cancellationToken);
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.ComponentModel;
using System.Reflection;
using EasilyNET.Core.Misc;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.ComponentModel;
using System.Reflection;

// ReSharper disable UnusedType.Global

Expand All @@ -16,11 +16,7 @@ namespace EasilyNET.WebCore.Swagger.SwaggerFilters;
// ReSharper disable once ClassNeverInstantiated.Global
public sealed class SwaggerDefaultValueFilter : ISchemaFilter
{
/// <summary>
/// Apply
/// </summary>
/// <param name="schema"></param>
/// <param name="context"></param>
/// <inheritdoc />
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema.Properties is null) return;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Reflection;
using EasilyNET.WebCore.Swagger.Attributes;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;

// ReSharper disable UnusedType.Global

Expand All @@ -12,25 +12,24 @@ namespace EasilyNET.WebCore.Swagger.SwaggerFilters;
/// </summary>
// ReSharper disable once UnusedMember.Global
// ReSharper disable once ClassNeverInstantiated.Global
public sealed class SwaggerHiddenApiFilter : IDocumentFilter
public sealed class SwaggerHiddenApiFilter : IDocumentAsyncFilter
{
/// <summary>
/// Apply
/// </summary>
/// <param name="swaggerDoc"></param>
/// <param name="context"></param>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
/// <inheritdoc />
public async Task ApplyAsync(OpenApiDocument swaggerDoc, DocumentFilterContext context, CancellationToken cancellationToken)
{
foreach (var apiDescription in context.ApiDescriptions)
await Task.Run(() =>
{
if (!apiDescription.TryGetMethodInfo(out var method) || (!method.ReflectedType!.IsDefined(typeof(HiddenApiAttribute)) && !method.IsDefined(typeof(HiddenApiAttribute)))) continue;
var key = $"/{apiDescription.RelativePath}";
if (key.Contains('?'))
foreach (var apiDescription in context.ApiDescriptions)
{
var index = key.IndexOf('?', StringComparison.Ordinal);
key = key[..index];
if (!apiDescription.TryGetMethodInfo(out var method) || (!method.ReflectedType!.IsDefined(typeof(HiddenApiAttribute)) && !method.IsDefined(typeof(HiddenApiAttribute)))) continue;
var key = $"/{apiDescription.RelativePath}";
if (key.Contains('?'))
{
var index = key.IndexOf('?', StringComparison.Ordinal);
key = key[..index];
}
_ = swaggerDoc.Paths.Remove(key);
}
_ = swaggerDoc.Paths.Remove(key);
}
}, cancellationToken);
}
}
15 changes: 8 additions & 7 deletions src/EasilyNET.WebCore.Swagger/SwaggerGenOptionsExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System.Reflection;
using EasilyNET.Core.Misc;
using EasilyNET.WebCore.Swagger.Attributes;
using EasilyNET.WebCore.Swagger.SwaggerFilters;
using Microsoft.AspNetCore.Builder;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
using System.Collections.Concurrent;
using System.Reflection;

// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
Expand All @@ -16,8 +17,8 @@ namespace Microsoft.Extensions.DependencyInjection;
/// </summary>
public static class SwaggerGenOptionsExtensions
{
private static readonly Dictionary<string, string> docsDic = [];
private static readonly Dictionary<string, string> endPointDic = [];
private static readonly ConcurrentDictionary<string, string> docsDic = [];
private static readonly ConcurrentDictionary<string, string> endPointDic = [];

/// <summary>
/// 添加预定于的Swagger配置
Expand All @@ -41,21 +42,21 @@ public static void EasilySwaggerGenOptions(this SwaggerGenOptions op, string def
{
//反射拿到值
var actionList = apiDescription.ActionDescriptor.EndpointMetadata.Where(x => x is ApiGroupAttribute).ToList();
if (actionList.Count != 0)
if (actionList.Count is not 0)
{
return actionList.FirstOrDefault() is ApiGroupAttribute attr && attr.Name == docName;
}
var not = apiDescription.ActionDescriptor.EndpointMetadata.Where(x => x is not ApiGroupAttribute).ToList();
return not.Count != 0 && docName == defaultDocName;
return not.Count is not 0 && docName == defaultDocName;
//判断是否包含这个分组
});
var files = Directory.GetFiles(AppContext.BaseDirectory, "*.xml");
foreach (var file in files)
{
op.IncludeXmlComments(file, true);
}
op.DocumentFilter<SwaggerHiddenApiFilter>();
op.OperationFilter<SwaggerAuthorizeFilter>();
op.DocumentAsyncFilter<SwaggerHiddenApiFilter>();
op.OperationAsyncFilter<SwaggerAuthorizeFilter>();
op.SchemaFilter<SwaggerDefaultValueFilter>();
}

Expand Down

0 comments on commit 9660388

Please sign in to comment.