Skip to content

Instantly share code, notes, and snippets.

@jenol
Last active August 21, 2019 17:43
Show Gist options
  • Save jenol/f7d0ad4f34221fbbd93f23bb34953bc7 to your computer and use it in GitHub Desktop.
Save jenol/f7d0ad4f34221fbbd93f23bb34953bc7 to your computer and use it in GitHub Desktop.
x-nullable for Swashbuckle
public class ApplySchemaVendorExtensions : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
if (type.IsArray && type.GetElementType() != typeof(byte))
{
// Special case
return;
}
var nullableUnderlyingType = Nullable.GetUnderlyingType(type);
if (nullableUnderlyingType != null && nullableUnderlyingType.IsValueType && !schema.vendorExtensions.ContainsKey("x-nullable"))
{
schema.vendorExtensions.Add("x-nullable", true);
}
if (schema.properties == null)
{
return;
}
foreach (var schemaProperty in schema.properties)
{
var property = type.GetProperty(schemaProperty.Key, BindingFlags.Public | BindingFlags.Instance);
if (property == null)
{
continue;
}
var propertyType = property.PropertyType;
Apply(schemaProperty.Value, schemaRegistry, propertyType);
}
}
}
namespace My
{
public class PhotoDto
{
public string Id { get; set; }
public string FileName { get; set; }
public string Src { get; set; }
public string ThumbnailSrc { get; set; }
public int TagId { get; set; }
public PhotoType PictureTypeId { get; set; }
public int? TestId { get; set; }
}
}
"My": {
"type": "object",
"properties": {
"CaptionId": {
"format": "int32",
"type": "integer"
},
"FileName": {
"type": "string"
},
"Id": {
"format": "int32",
"type": "integer"
},
"PictureTypeId": {
"enum": [
"Property",
"MainPhoto"
],
"type": "string"
},
"Src": {
"type": "string"
},
"ThumbnailSrc": {
"type": "string"
},
"TestId": {
"format": "int32",
"type": "integer",
"x-nullable": true
}
}
}
public class SwaggerConfig
{
public static void Register()
{
Register(GlobalConfiguration.Configuration);
}
public static void Register(SwaggerDocsConfig configuration)
{
// ... other settings
configuration.SchemaFilter();
// ... other settings
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment