如何设置Swagger默认值Example

前言

Swashbuckle.AspNetCore 版本<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />

设置 Example 默认值

经大佬指点:可以这样设置指定字段的默认值

/// <summary>
/// 用户名
/// </summary>
[Required(ErrorMessage = "用户名不能为空")]
[DefaultValue(" Hello")]
public string account { get; set; }
  1. 在实体上给定默认值
public class InputModel
{
    public string UserName { get; set; } = "userName";

    public string PassWord { get; set; } = "passWord";
}
  1. 实现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();
    }
}
  1. 注入到.net core 容器(Startup.cs)
public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(options =>
    {
        options.SchemaFilter<SchemaFilter>();
    }
}

最后

OK,这样就大功告成。

这是我的第一篇博客,哈哈,简陋了些。希望对大家有帮助!

posted @ 2020-09-17 09:53  一颗花生豆  阅读(9832)  评论(2编辑  收藏  举报