Skip to content

Instantly share code, notes, and snippets.

@GiorgioG GiorgioG/Startup.cs
Last active Feb 14, 2020

Embed
What would you like to do?
Snake Case support for Swashbuckle w/ ASP.NET Core 3.0
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = new SnakeCasePropertyNamingPolicy();
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1"});
c.SchemaFilter<SnakeCaseSchemaFilter>();
});
}
}
public class SnakeCasePropertyNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return name.ToSnakeCase();
}
}
public static class StringExtensions
{
public static string ToSnakeCase(this string str)
{
return string.Concat(str.Select((character, index) =>
index > 0 && char.IsUpper(character)
? "_" + character
: character.ToString()))
.ToLower();
}
}
public class SnakeCaseSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema.Properties == null) return;
if (schema.Properties.Count == 0) return;
var keys = schema.Properties.Keys;
var newProperties = new Dictionary<string, OpenApiSchema>();
foreach (var key in keys)
{
newProperties[key.ToSnakeCase()] = schema.Properties[key];
}
schema.Properties = newProperties;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.