as is
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace StopShopping.FileApi.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// 处理enum类型openapi显示
|
||||
/// </summary>
|
||||
public class EnumOpenApiSchemaTransformer : IOpenApiSchemaTransformer
|
||||
{
|
||||
public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
if (context.JsonTypeInfo.Type.IsEnum)
|
||||
{
|
||||
schema.Type = JsonSchemaType.Integer;
|
||||
|
||||
var enumValues = Enum.GetValues(context.JsonTypeInfo.Type)
|
||||
.Cast<object>()
|
||||
.Select(v => JsonNode.Parse(Convert.ToInt32(v).ToString())!)
|
||||
.ToList();
|
||||
|
||||
schema.Enum = enumValues;
|
||||
|
||||
var enumNames = Enum.GetNames(context.JsonTypeInfo.Type);
|
||||
schema.Extensions ??= new Dictionary<string, IOpenApiExtension>();
|
||||
var namesExtension = new JsonNodeExtension(new JsonArray(
|
||||
enumNames
|
||||
.Select(n => (JsonNode)n)
|
||||
.ToArray()));
|
||||
schema.Extensions.Add("x-enumNames", namesExtension);
|
||||
|
||||
var descMap = new JsonObject();
|
||||
foreach (var name in enumNames)
|
||||
{
|
||||
if (context.JsonTypeInfo.Type.GetField(name)
|
||||
?.GetCustomAttributes(typeof(DescriptionAttribute), false)
|
||||
.FirstOrDefault() is DescriptionAttribute attr)
|
||||
{
|
||||
descMap[name] = attr.Description;
|
||||
}
|
||||
}
|
||||
schema.Extensions.Add("x-enumDescriptions", new JsonNodeExtension(descMap));
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user