ServiceComposer.AspNetCore

Custom JSON response serialization settings

Available starting with v1.8.0

By default, each response is serialized using Json.Net and serialization settings (JsonSerializerSettings) are determined by the requested response casing. If the requested casing is camel casing, the default, the folowing serialization settings are applied to the response:

var settings = new JsonSerializerOptions()
{
    // System.Text.Json requires both properties to be
    // set to properly format serialized responses
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
};

snippet source | anchor

If the requested case is pascal, the following settings are applied:

var settings = new JsonSerializerOptions();

snippet source | anchor

It’s possible to customize the response serialization settings on a case-by-case using the following configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRouting();
    services.AddViewModelComposition(options =>
    {
        options.ResponseSerialization.UseCustomJsonSerializerSettings(_ =>
        {
            return new JsonSerializerOptions()
            {
                // customize options as needed
            };
        });
    });
}

snippet source | anchor

Each time ServiceComposer needs to serialize a response it’ll invoke the supplied function.

[!NOTE] When customizing the serialization settings, it’s responsibility of the function to configure the correct resolver for the requested casing