Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support conditionally (e.g. via a global flag) excluding properties in schema generation #1764

Open
ph3rin opened this issue Dec 22, 2024 · 0 comments

Comments

@ph3rin
Copy link

ph3rin commented Dec 22, 2024

I have a use-case where we decide to include/exclude certain properties from the schema based on a global flag.

My current workaround is to use a custom ISchemaProcessor to strip properties. However, that requires iterating through all properties of the ContextualType, generating a name for the property, and then remove it from the property dictionary:

var flag = true;
var settings = new SystemTextJsonSchemaGeneratorSettings();
if (flag)
{
    settings.SchemaProcessors.Add(new CustomIgnoreProcessor());
}

class MyClass
{
    public int Foo { get; set; }
    [CustomIgnore]
    public bool Bar { get; set; }
}

class CustomIgnoreAttribute : Attribute
{
}

class CustomIgnoreProcessor : ISchemaProcessor
{
    public void Process(SchemaProcessorContext context)
    {
        if (!context.Schema.IsObject) return;
        
        foreach (var property in context.ContextualType.Properties)
        {
            if (property.GetAttribute<CustomIgnoreAttribute>(true) == null)
            {
                continue;
            }
                
            var name = context
                .Generator.Settings.ReflectionService
                .GetPropertyName(property, context.Generator.Settings);
            context.Schema.Properties.Remove(name);
        }
    }
}

In the example above, CustomIgnore will only take effect if flag is being set to true.

Maybe there is a more elegant way. Currently the awkwardness mainly stems from not being able to get a JsonSchemaProperties's associated ContextualPropertyInfo. Maybe we can include it in the schema (as a nullable property because schemas aren't necessarily created from types).

@ph3rin ph3rin changed the title Support conditionally (i.e. via a global flag) excluding properties in schema generation Support conditionally (e.g. via a global flag) excluding properties in schema generation Dec 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant