Skip to content

Instantly share code, notes, and snippets.

@gubenkoved
Created November 23, 2017 18:21
Show Gist options
  • Save gubenkoved/e4a14f737255a8c5931ec6f1cd95f532 to your computer and use it in GitHub Desktop.
Save gubenkoved/e4a14f737255a8c5931ec6f1cd95f532 to your computer and use it in GitHub Desktop.
Swagger Operation Filter to handle FormData
// Usage:
// 1. Install-Package MultipartDataMediaFormatter.V2
// 2. Alter Swagger Config
// c.OperationFilter<FormDataOperationFilter>();
// 3. Annotate method you want to expose with multipart/form-data with [SwaggerMultipartAnnotatorAttribute]
public class FormDataOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
bool isMultipart = apiDescription.ActionDescriptor.GetCustomAttributes<SwaggerMultipartAnnotatorAttribute>().Any();
if (isMultipart)
{
operation.consumes.Add("multipart/form-data");
var parameters = new List<Parameter>();
operation.parameters = parameters;
foreach (var p in apiDescription.ActionDescriptor.GetParameters())
{
bool isFromBody = p.GetCustomAttributes<FromBodyAttribute>().Any();
if (isFromBody)
{
var properties = p.ParameterType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);
foreach (var prop in properties)
{
string type;
if (prop.PropertyType.Equals(typeof(HttpFile)))
{
type = "file";
} else
{
var registry = schemaRegistry.GetOrRegister(prop.PropertyType);
type = registry.type;
}
bool isRequired = prop.GetCustomAttributes<RequiredAttribute>().Any();
parameters.Add(
new Parameter
{
name = ToCamelCase(prop.Name),
@in = "formData",
type = type,
required = isRequired,
});
}
} else
{
var registry = schemaRegistry.GetOrRegister(p.ParameterType);
parameters.Add(new Parameter
{
name = p.ParameterName,
@in = "query",
type = registry.type,
required = !p.IsOptional,
});
}
}
}
}
private static string ToCamelCase(string value)
{
if (string.IsNullOrEmpty(value))
return value;
return value.Substring(0, 1).ToLowerInvariant() + value.Substring(1);
}
}
[AttributeUsage(AttributeTargets.Method)]
public class SwaggerMultipartAnnotatorAttribute : Attribute
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment