Created
November 23, 2017 18:21
-
-
Save gubenkoved/e4a14f737255a8c5931ec6f1cd95f532 to your computer and use it in GitHub Desktop.
Swagger Operation Filter to handle FormData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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