Last active
May 30, 2023 15:45
-
-
Save AndyButland/b76b5a782ddb8df2813b68d63ea4d408 to your computer and use it in GitHub Desktop.
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
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