这是一个简单的解决方法,如下所示:
1.安装Swashbuckle.AspNetCore.SwaggerGen 5.0.0-rc5
2.自定义SwaggerExcludeAttribute:
[AttributeUsage(AttributeTargets.Property)]
public class SwaggerExcludeAttribute : Attribute
{
}
3.自定义SwaggerExcludeFilter:
public class SwaggerExcludeFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema?.Properties == null)
{
return;
}
var excludedProperties =
context.Type.GetProperties().Where(
t => t.GetCustomAttribute<SwaggerExcludeAttribute>() != null);
foreach (var excludedProperty in excludedProperties)
{
var propertyToRemove =
schema.Properties.Keys.SingleOrDefault(
x => x.ToLower() == excludedProperty.Name.ToLower());
if (propertyToRemove != null)
{
schema.Properties.Remove(propertyToRemove);
}
}
}
}
4.在Startup.cs中注册:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.SchemaFilter<SwaggerExcludeFilter>();
});
services.AddDbContext<WebApi3_1Context>(options =>
options.UseSqlServer(Configuration.GetConnectionString("WebApi3_1Context")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
5.测试我的模型:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
[SwaggerExclude]
public Item Item { get; set; }
}
public class Item
{
public int Id { get; set; }
public string ItemName { get; set; }
public List<Person> Person { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}