ASP.NET Core Appsettings.JSON Update in Code

ASP.NET Core appsettings.json update in code

Here is a relevant article from Microsoft regarding Configuration setup in .Net Core Apps:

Asp.Net Core Configuration

The page also has sample code which may also be helpful.

Update

I thought In-memory provider and binding to a POCO class might be of some use but does not work as OP expected.

The next option can be setting reloadOnChange parameter of AddJsonFile to true while adding the configuration file and
manually parsing the JSON configuration file and making changes as intended.

    public class Startup
{
...
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
...
}

... reloadOnChange is only supported in ASP.NET Core 1.1 and higher.

Is there any way to Read & Update appSettings.json file from any controller method to save usersettings in ASP.NET Core 2 MVC

First of all, it's a bad idea to persist user settings into appsettings.json. The OS process executing your MVC app should never have write permission to this file for security reasons.

I would probably use a DB engine with ACID capabilities for this purpose. However, it could be ok to store such user settings in the file system - but in a separate file, at a safe location.

For example I'd create a folder named say App_Data in the application root folder, set write permission to it and place an adminsettings.json file into it. Then I'd use this file as my persistent storage for the said user settings.

Obviously, it would require some coding to make all this work. I put together a code sample for you which aims to reuse the configuration and options API of .NET Core. I think it exceeds the size acceptable here, so I made it available as a Gist.



Related Topics



Leave a reply



Submit