/// <summary>
/// cf. https://github.com/domaindrivendev/Swashbuckle/issues/69
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class SwaggerDefaultValueAttribute : Attribute
{
public string ParameterName { get; set; }
public object Value { get; set; }
public SwaggerDefaultValueAttribute(string paramName, string value)
{
this.ParameterName = paramName;
this.Value = value;
}
public SwaggerDefaultValueAttribute(string paramName, int value)
{
this.ParameterName = paramName;
this.Value = value;
}
}
public class SwaggerDefaultValueFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
foreach (var param in operation.parameters)
{
var actionParam = apiDescription.ActionDescriptor
.GetParameters()
.FirstOrDefault(p => p.ParameterName == param.name);
if (actionParam != null)
{
var customAttribute = actionParam.ActionDescriptor
.GetCustomAttributes<SwaggerDefaultValueAttribute>()
.FirstOrDefault(o => o.ParameterName == actionParam.ParameterName);
if (customAttribute != null)
{
param.@default = customAttribute.Value;
}
}
}
}
}
/// <summary>
/// swagger에서 API 호출에 필요한 매개변수(모델) 기본값을 생성해서 보여주는 필터 클래스.
/// </summary>
public class SwaggerSchemaExample : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
object example = null;
if (type == typeof(Product))
{
example = new Product
{
Id = "Abc",
Name = "GoGo"
};
}
schema.example = ToCamelCaseObject(example); // 객체 그대로 넣으면 PascalCase로 보이는 문제가 있음.
}
public static object ToCamelCaseObject(object obj)
{
var json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
});
return JsonConvert.DeserializeObject(json);
}
}
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SchemaFilter<SwaggerSchemaExample>();
c.OperationFilter<SwaggerDefaultValueFilter>();
});
}
}