domaindrivendev / Swashbuckle.AspNetCore

Swagger tools for documenting API's built on ASP.NET Core
MIT License
5.22k stars 1.3k forks source link

Removing A Property IParameterFilter #1297

Closed louislewis2 closed 2 days ago

louislewis2 commented 4 years ago

Hi,

Read only properties on models being used on classes for binding query parameters are still being displayed and are not marked read only or not displayed.

Is there a filter which I can use to prevent these properties from displaying?

Thanks

nathan-fieldstack-com commented 3 years ago

I have a similar problem. I would like to remove certain properties from the swagger document output, and an IParameterFilter seems the best place to do it. However, there doesn't seem to be a way to suppress a parameter from inside the filter.

I can remove the parameter with an IDocumentFilter, but by that point the reflection information is lost from the parameters.

nathan-fieldstack-com commented 3 years ago

I'm not sure if this would work for all use cases, but I was able to solve my problem using an IOperationFilter. That gave me access to both the reflection information of the method parameters and the swagger parameters.

My use case was (roughly) implementing a custom version of the BindNeverAttribute for [FromQuery] parameters. Here was my code:

public class MyOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var propertiesToRemove = context.MethodInfo.GetParameters()
            .Where(methodParm => methodParm.GetCustomAttribute(typeof(FromQueryAttribute), true) != null)
            .SelectMany(methodParm => methodParm.ParameterType.GetProperties())
            .Where(ShouldRemove)
            .Select(prop => prop.Name)
            .ToHashSet(StringComparer.InvariantCultureIgnoreCase);

        foreach (var parm in operation.Parameters.ToList())
        {
            if (propertiesToRemove.Contains(parm.Name))
            {
                operation.Parameters.Remove(parm);
            }
        }
    }

    private static bool ShouldRemove(PropertyInfo property)
    {
        return property.GetCustomAttribute(typeof(MyCustomBindNeverAttribute)) != null;
    }
}
jgarciadelanoceda commented 2 days ago

The latest versions have the SwaggerIgnore attribute for this and others cases. Added in #2610 @martincostello we can close this issue