-
-
Save Dmdv/aa2dfb2aaa2a05f68c5d938c2009edc2 to your computer and use it in GitHub Desktop.
Snake Case support for Swashbuckle w/ ASP.NET Core 3.0
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
| 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