How to define default values for parameters for the Swagger UI?

孤者浪人 提交于 2019-12-06 06:28:50

To define default values for parameters for Swagger UI in .NET Core, the following article defines a custom schema filter for your DefaultValue attribute in your Model class. The code shown below has been taken from this article and is purely to inform anyone else who has this question or has been facing a similar problem:

Decorate the desired properties in a model:

public class Test {
    [DefaultValue("Hello")]
    public string Text { get; set; }
}

Main filter:

using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Project.Swashbuckle {

    public class SchemaFilter : ISchemaFilter {

        public void Apply(Schema schema, SchemaFilterContext context) {
            if (schema.Properties == null) {
                return;
            }

            foreach (PropertyInfo propertyInfo in context.SystemType.GetProperties()) {

                // Look for class attributes that have been decorated with "[DefaultAttribute(...)]".
                DefaultValueAttribute defaultAttribute = propertyInfo
                    .GetCustomAttribute<DefaultValueAttribute>();

                if (defaultAttribute != null) {
                    foreach (KeyValuePair<string, Schema> property in schema.Properties) {

                        // Only assign default value to the proper element.
                        if (ToCamelCase(propertyInfo.Name) == property.Key) {
                            property.Value.Example = defaultAttribute.Value;
                            break;
                        }
                    }
                }
            }
        }

        private string ToCamelCase(string name) {
            return char.ToLowerInvariant(name[0]) + name.Substring(1);
        }
    }
}

And finally registering it to your Swagger Options(In Startup.cs):

services.AddSwaggerGen(c => {
    // ...
    c.SchemaFilter<SchemaFilter>();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!