Swashbuckle多态配置对外部Adyen Nuget包不生效的解决方法咨询
解决Adyen支付响应多态类型Swagger文档生成异常问题
完整配置方案
1. 调整SwaggerGen基础配置
在AddSwaggerGen方法中补充多态子类型映射、鉴别器配置,同时注册自定义Schema过滤器:
using Adyen.Model.Checkout.Action; services.AddSwaggerGen(c => { c.EnableAnnotations(); // 启用多态与继承支持 c.UseOneOfForPolymorphism(); c.UseAllOfForInheritance(); // 配置IPaymentResponseAction的所有子类型 c.SelectSubTypesUsing(baseType => { if (baseType == typeof(IPaymentResponseAction)) { return new[] { typeof(CheckoutAwaitAction), typeof(CheckoutDonationAction), typeof(CheckoutOneTimePasscodeAction), typeof(CheckoutQrCodeAction), typeof(CheckoutRedirectAction), typeof(CheckoutSDKAction), typeof(CheckoutThreeDS2Action), typeof(CheckoutVoucherAction) }; } return Enumerable.Empty<Type>(); }); // 配置多态鉴别器字段 c.SelectDiscriminatorNameUsing(baseType => baseType == typeof(IPaymentResponseAction) ? "type" : null); // 配置鉴别器值与子类型的映射关系 c.SelectDiscriminatorValueUsing(subType => { return subType.Name switch { nameof(CheckoutAwaitAction) => "await", nameof(CheckoutDonationAction) => "donation", nameof(CheckoutOneTimePasscodeAction) => "oneTimePasscode", nameof(CheckoutQrCodeAction) => "qrCode", nameof(CheckoutRedirectAction) => "redirect", nameof(CheckoutSDKAction) => "sdk", nameof(CheckoutThreeDS2Action) => "threeDS2Action", nameof(CheckoutVoucherAction) => "voucher", _ => null }; }); // 注册自定义Schema过滤器,处理外部Nuget类型属性扫描 c.SchemaFilter<AdyenActionSchemaFilter>(); // 可选:如果Adyen包有附带XML注释,可引入补充字段说明 var adyenXmlPath = Path.Combine(AppContext.BaseDirectory, "Adyen.xml"); if (File.Exists(adyenXmlPath)) { c.IncludeXmlComments(adyenXmlPath, true); } });
2. 实现自定义Schema过滤器
该过滤器用于解决Swashbuckle默认不扫描外部Nuget包类型属性的问题:
using System.Reflection; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Adyen.Model.Checkout.Action; public class AdyenActionSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 仅处理IPaymentResponseAction的实现类 if (!typeof(IPaymentResponseAction).IsAssignableFrom(context.Type) || context.Type == typeof(IPaymentResponseAction)) { return; } // 清空错误的基类引用 schema.AllOf.Clear(); // 扫描类型所有公共属性生成Schema var publicProperties = context.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in publicProperties) { if (schema.Properties.ContainsKey(property.Name)) { continue; } var propertySchema = context.SchemaGenerator.GenerateSchema( property.PropertyType, context.SchemaRepository); schema.Properties.Add(property.Name, propertySchema); // 标记必填字段 if (property.GetCustomAttribute<System.ComponentModel.DataAnnotations.RequiredAttribute>() != null) { schema.Required.Add(property.Name); } } } }
效果说明
配置完成后,Swagger会正确生成所有Action子类型的完整字段结构,多态鉴别器可以正常工作,自动生成的客户端代码也能正确识别不同的Action类型。
内容的提问来源于stack exchange,提问作者Joris Mathijssen
相关产品推荐
相关产品推荐

