Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using ConfigurationBuilder and appsettings.json, is it possible to set custom property binding?

Pretty standard procedure for manual configuration wire up

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .Build();

Then I call

var procSettings = builder.GetSection(ProcessSettings.SectionName).Get<ProcessSettings>();

Some data does not load. And I know why - some properties don't match to JSON attributes. I tried to decorate it with [JsonPropertyName("captureTrace")] thinking that microsoft would use its own binding (System.Text.Json.Serialization). But no! Do they really use property name and not checking the attributes? Basically, is there a way to do it - have property name different from the JSON property name?

Max I found

.Get<ProcessSettings>(x => new BinderOptions().BindNonPublicProperties = true);

Also, in my case I have the nested class, where other classes contain groups of properties within it.

like image 517
T.S. Avatar asked Sep 01 '25 01:09

T.S.


1 Answers

You can decorate the property with [ConfigurationKeyName]

For example:

public record class ProcessSettings
{
    [ConfigurationKeyName("any name")]
    public string CaptureTrace { get; set; }
}

appsettings.json:

{
  "MyProcessSettings": {
    "any name": "AnyValue"
  }
}

test:

using Microsoft.Extensions.Configuration;

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .Build();

var setting = builder
    .GetSection("MyProcessSettings")
    .Get<ProcessSettings>();

Console.WriteLine(setting);

output:

ProcessSettings { CaptureTrace = AnyValue }
like image 185
TZU Avatar answered Sep 02 '25 15:09

TZU