Edit an Asp.Net core settings from an API call?

Viewed 168

We are building a web app(asp.net core + angular) and we have some settings(like email server+username, mongoDb connection string, ...) that are required for the application to work properly.

The web app will be only an intranet app, and will be deployed by the customers on multiple location.

We wish that we could have a wizard when starting the web app(a bit like all those good old PHP website(wordpress like)), that would initialize the server configuration.

So my question: Is it possible, from a API call, to set some configuration(that will be persistent)? A bit like settings a config file to be reused?

EDIT With the help of @ParsaS, I managed to edit the appsettings.json, but in my program.cs, I get most of what is using my configuration, that doesn't reload those settings:

MongoDbSettings dbSettings = configuration.GetSection(MongoDbSettings.SECTION_NAME).Get<MongoDbSettings>();
        services.AddIdentityMongoDbProvider<User, Role, Guid>(
            identityOption => { identityOption.Password.RequiredLength = 8; },
            mongoOptions => { mongoOptions.ConnectionString = dbSettings.ConnectionString;});

(here typically the dbSettings.ConnectionString that I would like to edit).

Is there a way to re-run/re-start this?

3 Answers

Yes the ASP is using a JSON file to store the settings (appSettings.json) so you can modify the file run-time eg.

var configFile = _environment.ContentRootFileProvider.GetFileInfo("app.settings.json").PhysicalPath;
var configJson = JsonDocument.Parse(System.IO.File.ReadAllText(configFile));
var doc = configJson.RootElement.Add("key", myData);
System.IO.File.WriteAllText(configFile, doc.RootElement.GetRawText());

public static JsonDocument Add(this JsonElement element, string property, object value)
    {
      if (element.ValueKind != JsonValueKind.Object)
        return null;

      var dic = element.GetRawText().Deserialize<Dictionary<string, object>>();
      dic[property] = value;
      return JsonDocument.Parse(dic.Serialize());
    }

have look at these documents to learn how should modify JSON objects Json Document and Json.net

Here is what I've done:

In my Program.cs, instead of having everything, without a class or method, I created two methods and I rebuild and rerun the app when it stops:

public static void Main(string[] args)
{
    do
    {
        try
        {
            WebApplication app = Build(args);
            Run(app);
        }
        catch (Exception ex)
        { 
            Console.WriteLine(ex.ToString());
        }
    } while (true);
}

I inject in my controllers: IHostApplicationLifetime applicationLifetime

then when I need to reboot:

_applicationLifetime.StopApplication();

as you know how to change appsetting file , the only thing you need is to reload your program.cs according to this answer this is how you can do it

public class Program
    {
        private static CancellationTokenSource cancelTokenSource = new System.Threading.CancellationTokenSource();
        public static void Main(string[] args)
        {
            
            var host = CreateHostBuilder(args).Build();
            host.RunAsync(cancelTokenSource.Token).GetAwaiter().GetResult();
        }
        public static void Shutdown()
        {
            cancelTokenSource.Cancel();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

then call

Program.shutdown();
Related