Skip to content

Instantly share code, notes, and snippets.

@Vic-Chang
Last active September 22, 2022 06:10
Show Gist options
  • Save Vic-Chang/966dd3daa5b496aafb9878b5a3e90c39 to your computer and use it in GitHub Desktop.
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.
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