New backoffice/add system text json configuration attribute (#12998)
* Add SystemTextJsonConfigurationAttribute * Fix up formatting * Rename classes for clearer purpose Co-authored-by: Zeegaan <nge@umbraco.dk>
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Umbraco.Cms.ManagementApi.Filters;
|
||||
|
||||
namespace Umbraco.Cms.ManagementApi.Controllers;
|
||||
|
||||
[ManagementApiJsonConfiguration]
|
||||
public class ManagementApiControllerBase : Controller
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace Umbraco.Cms.ManagementApi.Filters;
|
||||
|
||||
public class ManagementApiJsonConfigurationAttribute : TypeFilterAttribute
|
||||
{
|
||||
public ManagementApiJsonConfigurationAttribute() : base(typeof(SystemTextJsonConfigurationFilter)) =>
|
||||
Order = 1; // Must be low, to be overridden by other custom formatters, but higher then all framework stuff.
|
||||
|
||||
private class SystemTextJsonConfigurationFilter : IResultFilter
|
||||
{
|
||||
public void OnResultExecuted(ResultExecutedContext context)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnResultExecuting(ResultExecutingContext context)
|
||||
{
|
||||
if (context.Result is ObjectResult objectResult)
|
||||
{
|
||||
var serializerOptions = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
};
|
||||
objectResult.Formatters.Clear();
|
||||
objectResult.Formatters.Add(new ManagementApiJsonOutputFormatter(serializerOptions));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.Mvc.Formatters;
|
||||
|
||||
namespace Umbraco.Cms.ManagementApi.Filters;
|
||||
|
||||
public class ManagementApiJsonOutputFormatter : SystemTextJsonOutputFormatter
|
||||
{
|
||||
public ManagementApiJsonOutputFormatter(JsonSerializerOptions jsonSerializerOptions) : base(RegisterJsonConverters(jsonSerializerOptions))
|
||||
{
|
||||
}
|
||||
|
||||
protected static JsonSerializerOptions RegisterJsonConverters(JsonSerializerOptions serializerOptions)
|
||||
{
|
||||
serializerOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
|
||||
return serializerOptions;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user