Asp net core appsettings json update in code


ASP.NET is a popular programming language used for building web applications. One common task in ASP.NET development is the .json file in code. This article will provide a solution to this with examples.

Updating appsettings.json in ASP.NET Core

In ASP.NET Core, the appsettings.json file is used to store configuration settings for the application. To update this file programmatically, you can use the IConfiguration provided by the Microsoft.Extensions.Configuration package.

, you need to add a reference to the Microsoft.Extensions.Configuration package in your project. You can do this by adding the following line to your project's .csproj file:

Once you have added the package reference, you can use the IConfiguration interface to read and update the appsettings.json file. Here's an example:

using .IO;

public class AppSettingsUpdater
    private readonly IConfiguration _configuration;

    public AppSettingsUpdater()
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: , reloadOnChange: true);

        _configuration = builder.Build();

    public void UpdateSetting( key, string value)
        _configuration[key] = value;

        var builder = new ConfigurationBuilder()

        var newConfiguration = builder.Build();

        using (var stream = new StreamWriter("appsettings.json"))

In the above example, we create an instance of the IConfiguration interface by the appsettings.json file. We then update the desired setting by modifying the IConfiguration object. Finally, we rebuild the configuration and write it back to the appsettings.json file.


To use the AppSettingsUpdater class, you can create an instance of it and call the UpdateSetting method with the key and value of the setting you want to update. Here's an example:

var updater = new AppSettingsUpdater();
updater.UpdateSetting("MySetting", "NewValue");

In the above example, we create an instance of the AppSettingsUpdater class and call the UpdateSetting method to update the “MySetting” key with the value “NewValue”.


Updating the appsettings.json file in code is a common task in ASP.NET development. By using the IConfiguration interface provided by the Microsoft.Extensions.Configuration package, you can easily read and update the configuration settings. The example provided in this article demonstrates how to update a setting in the appsettings.json file programmatically.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents