asp.net-coreswaggeropenapiswashbuckleswashbuckle.aspnetcore

Swagger, ignore property when generating actions. To resolve conflict for Property Type


I am using Swashbuckle 5.6.3 on ASP.Net Core.

I'm getting this error: Failed to generate Operation for action

Tracing the problem, it is because I have a conflict on the property type of the response:

public class Product {
    public string name {get; set;}
    ..... more properties....
    public Reverb.Product ReverbProduct {get; set;} // HERE IS MY PROBLEM
}

We have both Product and Reverb.Product property types, which it's not liking.

The class Reverb.Product is used internally within my application and I have no need for it to exposed to the API, so I have written a schema filter using an Attribute:

[AttributeUsage(AttributeTargets.Property)]
public class SwaggerExcludeAttribute : Attribute
{
}

public class SwaggerExcludeFilter : ISchemaFilter
{
    private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        var type = context?.Type; 
        if (schema?.Properties == null || type == null)
            return;

        var excludedProperties = type.GetProperties()
                                     .Where(t =>
                                            t.GetCustomAttribute<SwaggerExcludeAttribute>()
                                            != null);

        foreach (var excludedProperty in excludedProperties)
        {
            if (schema.Properties.ContainsKey(excludedProperty.Name))
                schema.Properties.Remove(excludedProperty.Name);
        }
        l.Report(schema.Dump(false), AlwaysLog: true);
    }
}

This code was written using various help I found on SO and others (had some version conflict, but resolved...!)

However, this doesn't fix my error.

So, I guess that whilst the SchemaFilter might stop this property being exposed to my API, it is not stopping Swashbuckle from trying to resolve this property type when generating operations.

Is there any way to make it ignore this property altogether, not just in the schema?


Solution

  • I found a solution (CustomSchemaIds) on this question:

    swagger error: Conflicting schemaIds: Duplicate schemaIds detected for types A and B

    services.ConfigureSwaggerGen(options =>
    {
       // your custom configuration goes here
       ...
         // UseFullTypeNameInSchemaIds replacement for .NET Core
        options.CustomSchemaIds(x => x.FullName);
    });
    

    However this fully qualifies the property, rather than ignoring it.

    So I still don't have a viable solution to that question.