Default model example in Swashbuckle (Swagger)

前端 未结 5 1802
再見小時候
再見小時候 2020-12-08 05:22

I\'m running ASP WebAPI 2 and successfully installed Swashbuckle. I am trying to figure out how one defines what the default schema values are?

For example, on the S

5条回答
  •  暖寄归人
    2020-12-08 05:47

    I know this thread is quite old, but I wanted to share my solution which creates a custom constructor just for the Swagger example schema.

    In my model:

    /// 
    /// Supply a custom constructor for Swagger where you can apply defaults to control the example schema.  
    /// The constructor must have one parameter of type System.Reflection.ParameterInfo[].
    /// Note: Setting a property to null will prevent it from showing in the Swagger example.
    /// System.Reflection.ParameterInfo[].
    /// 
    public class SwaggerConstructor : Attribute { }
    

    In SwaggerConfig.cs:

    c.SchemaFilter();
    

    The schema extension:

        public class ApplySchemaVendorExtensions : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            ConstructorInfo constructor = type.GetConstructors().FirstOrDefault(c => c.GetCustomAttribute() != null);
            if (constructor != null)
            {
                schema.example = constructor.Invoke(new object[] { constructor.GetParameters() });
            }
        }
    }
    

    Usage:

        [SwaggerConstructor]
        public MyClass(System.Reflection.ParameterInfo[] decoy) : base()
        {
            MyProperty = false;
        }
    

提交回复
热议问题