How to configure Swashbuckle to ignore property on model

后端 未结 15 1772
旧巷少年郎
旧巷少年郎 2020-12-02 15:10

I\'m using Swashbuckle to generate swagger documentation\\UI for a webapi2 project. Our models are shared with some legacy interfaces so there are a couple of properties I

15条回答
  •  感动是毒
    2020-12-02 16:03

    I get inspired by the blog of Ignoring properties from controller action model in Swagger using JsonIgnore.

    I'm using .net core 2.1 and Swashbuckle.AspNetCore 5.3.1. The code below solved the problem.

    Add a new filter

    public class SwaggerJsonIgnoreFilter : IOperationFilter
        {
            public void Apply(OpenApiOperation operation, OperationFilterContext context)
            {
                var ignoredProperties = context.MethodInfo.GetParameters()
                    .SelectMany(p => p.ParameterType.GetProperties()
                    .Where(prop => prop.GetCustomAttribute() != null))
                    .ToList();
    
                if (!ignoredProperties.Any()) return;
    
                foreach (var property in ignoredProperties)
                {
                    operation.Parameters = operation.Parameters
                        .Where(p => (!p.Name.Equals(property.Name, StringComparison.InvariantCulture)))
                        .ToList();
                }
            }
        }
    

    Use the Filter in Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
    
    ......
    
     services.AddSwaggerGen(options =>
                    {
                        options.SwaggerDoc("v1", new OpenApiInfo { Title = "CustomApi", Version = "v1" });
                        options.OperationFilter();
                    });
    
    ......
    
    }
    
    

提交回复
热议问题