如何設置Swagger默認值Example


前言

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

設置 Example 默認值

  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,這樣就大功告成。

這是我的第一篇博客,哈哈,簡陋了些。希望對大家有幫助!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。