コード例 #1
0
        /// <summary>
        /// Adds polymorphism.
        /// </summary>
        /// <param name="options">The options used to generate the swagger.json file.</param>
        /// <param name="services">Specifies the contract for a collection of service descriptors.</param>
        public static void AddPolymorphism(this SwaggerGenOptions options, IServiceCollection services)
        {
            var serviceProvider = services.BuildServiceProvider();
            var jsonOptions     = serviceProvider.GetService <IOptions <JsonOptions> >();

            if (jsonOptions == null)
            {
                return;
            }
            var jsonSerializerOptions = jsonOptions.Value.JsonSerializerOptions;
            var polymorphicConverters = jsonSerializerOptions?.Converters?.Where(x => {
                var converterType = x.GetType();
                if (!(converterType.IsGenericType && converterType.GetGenericTypeDefinition().IsAssignableFrom(typeof(JsonPolymorphicConverterFactory <>))))
                {
                    return(false);
                }
                return(true);
            })
                                        .Cast <IJsonPolymorphicConverterFactory>();

            if (!polymorphicConverters.Any())
            {
                return;
            }
            foreach (var converter in polymorphicConverters)
            {
                var baseType      = converter.BaseType;
                var discriminator = jsonSerializerOptions.PropertyNamingPolicy.ConvertName(converter.TypePropertyName);
                var mapping       = JsonPolymorphicUtils.GetTypeMapping(baseType, discriminator);
                options.SchemaFilter <PolymorphicSchemaFilter>(baseType, discriminator, mapping);
                options.OperationFilter <PolymorphicOperationFilter>(new PolymorphicSchemaFilter(baseType, discriminator, mapping));
            }
        }
コード例 #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JsonPolymorphicConverter{T}"/> class.
 /// </summary>
 /// <param name="typePropertName">The name of the property in which to serialize the type name.</param>
 public JsonPolymorphicConverter(string typePropertName) : this(typePropertName, JsonPolymorphicUtils.GetTypeMapping(typeof(T), typePropertName))
 {
 }