Skip to content

Instantly share code, notes, and snippets.

@AndyButland
Last active May 30, 2023 15:45
Show Gist options
  • Save AndyButland/b76b5a782ddb8df2813b68d63ea4d408 to your computer and use it in GitHub Desktop.
Save AndyButland/b76b5a782ddb8df2813b68d63ea4d408 to your computer and use it in GitHub Desktop.
public class MyApiControllerAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext ctx)
{
if (ctx.Result is ObjectResult objectResult)
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new MyApiContractResolver(),
};
settings.Converters.Add(new StringEnumConverter());
objectResult.Formatters.Add(new NewtonsoftJsonOutputFormatter(
settings,
ctx.HttpContext.RequestServices.GetRequiredService<ArrayPool<char>>(),
ctx.HttpContext.RequestServices.GetRequiredService<IOptions<MvcOptions>>().Value,
new MvcNewtonsoftJsonOptions()));
}
}
}
internal class MyApiContractResolver : DefaultContractResolver
{
public MyApiContractResolver() =>
NamingStrategy = new CamelCaseNamingStrategy
{
ProcessDictionaryKeys = true,
};
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties
.OrderBy(p => p.Order ?? int.MaxValue)
.ThenBy(p => p.PropertyName)
.ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment