C
C#2y ago
kaziux

✅ How to edit and save specific appsettings.json (project root) section?

Hello, I have issue with editing specific section in the appsettings.json in project root folder, but now it overwrites all he file although it should overwrite only the specific section

public void SetYear(int year)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build()
.Get<Config>();

config.ConfigurableYear = year;

var jsonWriteOptions = new JsonSerializerOptions()
{
WriteIndented = true,

};

var newJson = JsonSerializer.Serialize(config, jsonWriteOptions);

var appSettingsPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
File.WriteAllText(appSettingsPath, newJson);

}

public void SetYear(int year)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build()
.Get<Config>();

config.ConfigurableYear = year;

var jsonWriteOptions = new JsonSerializerOptions()
{
WriteIndented = true,

};

var newJson = JsonSerializer.Serialize(config, jsonWriteOptions);

var appSettingsPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
File.WriteAllText(appSettingsPath, newJson);

}
30 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
I use on the local env. This is service function which used on the api endpoint
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
nope, I do just API call.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
inside controller aka endpoint
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
public class ConfigService : IConfigService
{
private readonly Configs _configs;

public ConfigService(IOptions<Configs> configs)
{
_configs = configs.Value;
}

public void SetYear(int year)
{

_configs.ConfigurableYear = year;
}
}
public class ConfigService : IConfigService
{
private readonly Configs _configs;

public ConfigService(IOptions<Configs> configs)
{
_configs = configs.Value;
}

public void SetYear(int year)
{

_configs.ConfigurableYear = year;
}
}
Also, I do in this Startup.cs to bind this section
services.Configure<Configs>(options => Configuration.GetSection("ConfigurableYear").Bind(options));
services.Configure<Configs>(options => Configuration.GetSection("ConfigurableYear").Bind(options));
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX2y ago
appsettings.json:
{
"My": {
"Foo": {
"Kix": 5
}
}
}
{
"My": {
"Foo": {
"Kix": 5
}
}
}
src/Foo/FooOptions.cs:
public class FooOptions
{
public const string SectionName = "My:Foo";

public string Bar {get;set;} = "default value for bar";
public int Kix {get;set;} = -1;
public DateTime? Pouet {get;set;} = default;
}
public class FooOptions
{
public const string SectionName = "My:Foo";

public string Bar {get;set;} = "default value for bar";
public int Kix {get;set;} = -1;
public DateTime? Pouet {get;set;} = default;
}
src/Foo/FooServiceCollectionExtensions.cs:
namespace Microsoft.Extensions.DependencyInjection; // <==== recommanded for service.Add so that you don't clutter Startup file

public class FooServiceCollectionExtensions
{
public static IServiceCollection AddFoo(this IServiceCollection services) =>
services
.AddOptions<FooOptions>()
.BindConfiguration(FooOptions.SectionName)
.Validate(options => options.Kix >= 0, $"The configuration key '{FooOptions.SectionName}:{nameof(Kix)}' cannot be negative")
;

public static IServiceCollection AddFoo(this IServiceCollection services, Action<FooOptions> configure) =>
services
.AddFoo()
.Configure(configure);
namespace Microsoft.Extensions.DependencyInjection; // <==== recommanded for service.Add so that you don't clutter Startup file

public class FooServiceCollectionExtensions
{
public static IServiceCollection AddFoo(this IServiceCollection services) =>
services
.AddOptions<FooOptions>()
.BindConfiguration(FooOptions.SectionName)
.Validate(options => options.Kix >= 0, $"The configuration key '{FooOptions.SectionName}:{nameof(Kix)}' cannot be negative")
;

public static IServiceCollection AddFoo(this IServiceCollection services, Action<FooOptions> configure) =>
services
.AddFoo()
.Configure(configure);
Program.cs / Startup.cs:
services.AddFoo();
// or
services.AddFoo(fooOptions => fooOptions.Kix = 12);
services.AddFoo();
// or
services.AddFoo(fooOptions => fooOptions.Kix = 12);
Bar.cs:
public class Bar
{
private readonly FooOptions _fooOptions;

// .Value in ctor is fine only if it's always ever a non-changing value (no reload and/or no scoped resolution)
public Bar(IOptions<FooOptions> fooOptions)
=> _fooOptions = fooOptions.Value;
}
public class Bar
{
private readonly FooOptions _fooOptions;

// .Value in ctor is fine only if it's always ever a non-changing value (no reload and/or no scoped resolution)
public Bar(IOptions<FooOptions> fooOptions)
=> _fooOptions = fooOptions.Value;
}
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
But I must have option for user aka admin to set a value
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
because one of requirements make that value editable. So system admin must change value who can be non-tech person
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
value is must set configurable runtime
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
The case if for some reason you can't save the value sucessfully
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
That is the case I faced prieviously when value is saved on the bin/debug edition of the appsettings.json so the value be 1
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
It depends if have reload on change or not
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
If saved in the DB it would be fine but I'm not 100proc sure about some kind of the file
MODiX
MODiX2y ago
tebeco#0205
sounds like what Azure AppConfiguration does / could do
React with ❌ to remove this embed.
kaziux
kaziux2y ago
Much safer case have custom json with user configurable values
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kaziux
kaziux2y ago
Sorry, but I'm not hosting this project on the free Azure plan but if hosting would be the case, I must pretty aware of that.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts