42 lines
1.8 KiB
C#
42 lines
1.8 KiB
C#
using Microsoft.OpenApi.Models;
|
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
|
|
|
namespace NejCommon.Validation;
|
|
|
|
public class NejValidationAttributeFilter : ISchemaFilter
|
|
{
|
|
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
|
|
{
|
|
var type = context.Type;
|
|
var attrOnType = context.MemberInfo?.GetCustomAttributes(typeof(NejValidationAttribute), true)?.Select(a => a as NejValidationAttribute)?.FirstOrDefault();
|
|
if (attrOnType != null)
|
|
{
|
|
Console.WriteLine("Added examples for: " + context.MemberInfo?.Name);
|
|
schema.Example = OpenApiAnyFactory.CreateFromJson(attrOnType.ExampleJson);
|
|
attrOnType.ApplySchema(schema);
|
|
}
|
|
|
|
var attrOnType2 = context.ParameterInfo?.GetCustomAttributes(typeof(NejValidationAttribute), true)?.Select(a => a as NejValidationAttribute)?.FirstOrDefault();
|
|
if (attrOnType2 != null)
|
|
{
|
|
Console.WriteLine("Added examples for: " + context.ParameterInfo?.Name);
|
|
schema.Example = OpenApiAnyFactory.CreateFromJson(attrOnType2.ExampleJson);
|
|
attrOnType.ApplySchema(schema);
|
|
}
|
|
|
|
foreach (var prop in type.GetProperties())
|
|
{
|
|
if (schema.Properties.TryGetValue(prop.Name, out var pschema))
|
|
{
|
|
Console.WriteLine("Schema for: " + prop.Name);
|
|
var attr = prop.GetCustomAttributes(typeof(NejValidationAttribute), true).Select(a => a as NejValidationAttribute).FirstOrDefault();
|
|
if (attr != null)
|
|
{
|
|
Console.WriteLine("Added examples for: " + prop.Name);
|
|
pschema.Example = OpenApiAnyFactory.CreateFromJson(attr.ExampleJson);
|
|
attrOnType.ApplySchema(schema);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |