首页 > 其他分享 >设置Swagger默认值Example

设置Swagger默认值Example

时间:2022-11-03 09:11:26浏览次数:48  
标签:默认值 co public context sc Swagger Type Example

1、在实体上给定默认值

public class InputModel
{
    public string UserName { get; set; } = "userName";

    public string PassWord { get; set; } = "passWord";
}

2、实现ISchemaFilter接口

public class SchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (!context.Type.IsClass || context.Type == typeof(string) || !context.Type.IsPublic || context.Type.IsArray) return;
        var obj = Activator.CreateInstance(context.Type);
        _ = (from sc in schema.Properties
             join co in context.Type.GetProperties() on sc.Key.ToLower() equals co.Name.ToLower()
             select sc.Value.Example = co.GetValue(obj) != null ? OpenApiAnyFactory.CreateFor(sc.Value, co.GetValue(obj)) : sc.Value.Example).ToList();
    }
}

3、注入到.net core 容器(Startup.cs)

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(options =>
    {
        options.SchemaFilter<SchemaFilter>();
    }
}

 

标签:默认值,co,public,context,sc,Swagger,Type,Example
From: https://www.cnblogs.com/superfeeling/p/16853271.html

相关文章