| | | 1 | | #region Usings |
| | | 2 | | using System.Reflection; |
| | | 3 | | using Microsoft.OpenApi.Any; |
| | | 4 | | using Microsoft.OpenApi.Models; |
| | | 5 | | using Swashbuckle.AspNetCore.SwaggerGen; |
| | | 6 | | #endregion |
| | | 7 | | |
| | | 8 | | namespace ZhEaIsNsAaBn.Utilities.Swagger; |
| | | 9 | | |
| | | 10 | | /// <summary>Swashbuckle schema filter that copies <see cref="SwaggerSchemaExampleAttribute.Example"/> into the OpenAPI |
| | | 11 | | /// <example> |
| | | 12 | | /// <code> |
| | | 13 | | /// services.AddSwaggerGen( options => options.SchemaFilter<SwaggerSchemaExampleFilter>() ); |
| | | 14 | | /// </code> |
| | | 15 | | /// </example> |
| | | 16 | | public sealed class SwaggerSchemaExampleFilter : ISchemaFilter |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Sets <see cref="OpenApiSchema.Example"/> from the attribute on the property, else the parameter, else the schema |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="schema">The schema being generated.</param> |
| | | 22 | | /// <param name="context">The Swashbuckle context for the schema.</param> |
| | | 23 | | /// <exception cref="ArgumentNullException"><paramref name="schema"/> or <paramref name="context"/> is <see langword |
| | | 24 | | public void Apply( OpenApiSchema schema, SchemaFilterContext context ) |
| | | 25 | | { |
| | 72 | 26 | | ArgumentNullException.ThrowIfNull( schema ); |
| | 72 | 27 | | ArgumentNullException.ThrowIfNull( context ); |
| | | 28 | | |
| | | 29 | | |
| | 72 | 30 | | var attribute = context.MemberInfo?.GetCustomAttribute<SwaggerSchemaExampleAttribute>() |
| | 72 | 31 | | ?? context.ParameterInfo?.GetCustomAttribute<SwaggerSchemaExampleAttribute>() |
| | 72 | 32 | | ?? context.Type?.GetCustomAttribute<SwaggerSchemaExampleAttribute>(); |
| | | 33 | | |
| | | 34 | | |
| | 116 | 35 | | if ( attribute?.Example is not null ) { schema.Example = new OpenApiString( attribute.Example ); } |
| | 72 | 36 | | } |
| | | 37 | | } |