Last active
September 22, 2022 06:10
-
-
Save Vic-Chang/966dd3daa5b496aafb9878b5a3e90c39 to your computer and use it in GitHub Desktop.
.NET JSON naiming style attribute. A action attribute that converts JSON columns naming style.
This file contains 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
using System; | |
using System.Text.Json; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.AspNetCore.Mvc.Filters; | |
namespace Demo.Attributes | |
{ | |
public class JsonCamelCase : Attribute, IResultFilter | |
{ | |
private bool IsLowerCamelCase { get; } | |
public JsonCamelCase(bool isLowerCamelCase) | |
{ | |
IsLowerCamelCase = isLowerCamelCase; | |
} | |
public void OnResultExecuted(ResultExecutedContext context) | |
{ | |
} | |
public void OnResultExecuting(ResultExecutingContext context) | |
{ | |
try | |
{ | |
if (context.Result is JsonResult jsonResult) | |
{ | |
var options = new JsonSerializerOptions(); | |
if (jsonResult.SerializerSettings != null) | |
{ | |
options = jsonResult.SerializerSettings as JsonSerializerOptions; | |
} | |
options.PropertyNamingPolicy = IsLowerCamelCase ? JsonNamingPolicy.CamelCase : null; | |
jsonResult.SerializerSettings = options; | |
} | |
} | |
catch (Exception) | |
{ | |
// ignored | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment